Written by - Saksham Jain

React Component


A component is a powerful tool of React, through this we can break the interface into small parts and we can reuse these as many times we want and also we can change a single component when needed without changing the full website. We can use components inside other components or files using import-export. React give us two way to implement components:

  1. Class Components.
  2. Function Components. (*mostly used)

React class component:

We use ES6 classes to define Component and inherit React.Component class
Example
class Welcome extends React.Component {
    render() {
      return <h1>Hello World</h1>;
    }
  }

React function component:

This is the easiest way to define React Component. In this, we create a function and return JSX. Function components are almost the same as class components but it requires fewer lines of code.
Example
function Welcome() {
    return <h2>Hello World</h2>;
  }
 
  ReactDOM.render(<Welcome />, document.getElementById('root'));

Rendering a component:

We need to render components to add them into DOM.
Syntax for rendering :
ReactDOM.render(<Welcome />, document.getElementById('root'));
This will display the welcome component in the “root” element.

Props:

These are the properties of components. They are used to transfer data from one component to another. These are the same as attributes of elements. Props are read-only.
Example
function Car(props) {
    return <h2>Hello, I am {props.color}</h2>;
  }
 
  ReactDOM.render(<Car color="red"/>, document.getElementById('root'));

State:

The React class type component maintains an internal state that acts as its database. This state can be updated and each time it is changed, React displays that part.
Example
import React, { useState } from 'react';
const App = () => {
  const [count, setCount] = useState(0);
 
  return (
    <div className="container">
      <p>You clicked {count} times</p>
      <button
        onClick={() => setCount(count + 1)}>
        Click me!
      </button>
    </div>
  );
};