10. What is React Component

Components are independent and reusable bits of code. Components are like functions that return HTML elements. They serve same purpose as Javascript functions but work in isolation & return HTML


With React Components you must define render() method.

There are two type of components.

Class Components

Function Components

The React Class Component must include extends React.Component statement.

It will allow us to break into small reusable chunks. Each little components has its own set of JSX that it renders to the screen.

It can handle JSX elements.

 Figuring out how we might break them up into small logical reusable chunks.

We are going to think about individual thing of UI.

We use Headers, this little Header will be used in multiple places. And we will do custom html elements although technically they are called React Components.

We will create a parent component. This will be specific to this page.

Example:

<Mycomponent /> -> Parent component

Below are the child components.

<Header />

<Content />

<Option />

 

 Lets create our very first React Components.

app.js

With react component we must define render() method.

 
 class Header extends React.Component {
    render() {
      return (
        <div>
          <p>Hello, Welcome to Sleepycoder!</p>
        </div>
      );
    }
  }

     
const jsx = (<div>
        <Header /> //Add the Component like this way same as the class name
        <Header /> // These are custom HTML Elements.
    </div>);

    ReactDOM.render(jsx, document.getElementById('app'));


 <Header /> is referring to the above header class.

If we change to first letter as lowercase <header /> this will not be visible.

Nesting Components:

Componets inside the componet called sub component.

We are going to focus on rendering a new component inside of this one.

Create a root class and add all components.

Lets create a new components <Content />  and  <Option /> and add all components.

    
 class Content extends React.Component {
        render() {
        return (
            <div>
            <p>Content Component Here!</p>
            </div>
        );
        }
    }


    class Option extends React.Component {
        render() {
        return (
            <div>
            <h1>Option Component Here</h1>
            </div>
        );
        }
    }
 
    const jsx = (<div>
        <Header />
        <Content />
        <Option />
    </div>);

    ReactDOM.render(jsx, document.getElementById('app'));
 
 

 

 

Comments