React Components

Page Content:


  1. Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.
  2. Ideally, components are like JavaScript functions. They accept arbitrary inputs (we call “props”) and return React elements describing what should appear on the screen

2.Types of Components:

Basically, there are 2 types of Components in React

  1. Functional Component.
  2. Class Component.

1.Functional Component:

  • One of the simplest ways to write any react component is to write a javascript function.
  • we call such components are stateless components as we cant maintain any state inside the functional component.
  • But after React v16. 8.0. now we can use state inside functional component using hooks.

Let’s see how functional component looks like,

function myComponent(props) {
  return <h1>Hello {}</h1>;

This function is a valid react component that takes a single argument called props(we call it properties) & returns react element.

2.Class Component:

  • We can also write a react component using the javascript ES6 class. (We call it as class component)
  • The class component is a stateful component as we can maintain the state of the class.
  • class component internally uses this keyword.
class myComponent extends React.Component {
  render() {
    return <h1>Hello {}</h1>;

3.Rendering a Component:

Let’s discuss how react renders any component.

Now let’s create a custom react component.

function myComponent(props) {
  return <h1>Hello {}</h1>;

Now assign it to any element.

const element = <myComponent name="webdev99" />;

Now render this element using ReactDOM:


When React sees an element representing a custom component it passes JSX attributes to this component as a single object, we call it props.
Now react-dom renders element inside root element.

Above code will result into below view in the browser: