ReactJS #5: Write Simple React Component.

React Components are basic building blocks of any react apps and allow us to split our UI into a reusable piece of code which accepts data through properties and states and return HTML elements.

There are two ways we can define components in ReactJS.

  • The functions components using javascript
  • The class components using ES6 Classes

In this lab, we will covers :

  • How react components works.
  • How to write simple react component using Javascript functions
  • How to write simple react component using ES6 classes

So, let’s get started

Folder Structure:

First, we will create “components” folder inside “src” and then we will create one more folder named “lists” inside “components”.

c:/codebase/todo-app/
  
  node_modules/
  public/
  src/
  .../Components
  ............../lists

In the above code, we have created lists folder for “TodoLists” component. So, in the future, we will have a separate folder for each reacts component. This will help us to organize and make it easy to access all required stuff like unit test cases files, CSS, etc together for a particular component.

Function components

Function components are very easy to implement. Simply write a javascript function that returns the HTML elements.

Your first component

function TodoList() {
  return (
            <div className="todo-list">
                <h1>TodoLists</h1>
                <ul>
                    <li>Buy a big doll</li>
                    <li>Do yoga</li>
                    <li>Review component article</li>
                </ul>
            </div>
        );
}

function App() {
    return (
    <div>
      <TodoList/>
    </div>
  );
 }

ReactDOM.render(<App />, document.getElementById('root'));

Try it on CodePen

Passing properties to function component TodoList

let’s create an array of todos and pass it as props to TodoList component.

https://gist.github.com/rajgadade/7e55442478816adc52d450272944a460

We can render one component into other components. Now , render <TodoList> function component into <App> component

function App() {
    return (
    <div>
      <TodoList data={todos}/>
    </div>
  );
 }

ReactDOM.render(<App />, document.getElementById('root'));

Try it on CodePen

Output :

Write a simple class component using ES6 classes

import React from "react";
import  "./TodoLists.css";
export default class TodoList extends React.Component {
    render() {
        return (
            <div className="todo-list">
              <h1>TodoList</h1>
              <ul>
                <li>Buy a big doll</li>
                <li>Do yoga</li>
                <li>Review component article</li>
              </ul>
            </div>
        );
    }
}

Try it on codepen