React Elements vs Components

  • Note
    React Element

    An Element is an object that represents a DOM node it is a part of DOM structure

    React Element does not have any methods, making it light and faster to render than components.

    React Component

    It is independent and reusable. It returns the virtual DOM of the element. It contains elements and encapsulate logic, structure, and behavior for parts of your UI.

    Difference between Element and Component

    ElementComponent
    The element does not have any methods. Each component has its methods.
    A React element is an object representation of a DOM node. A component encapsulates a DOM tree.
    Elements are immutable i,e once created cannot be changed. The state in a component is mutable.

    How to create element and components

    Element

    create element

    
                      const myHeading = <h1>Welcome to my React app!</h1>;
                

    Rendering the element to the DOM:

    
                      ReactDOM.render(myHeading, document.getElementById('root'));
                
    Componenet

    create component

    
    
                // Functional component:
    function WelcomeMessage(props) {
      return <h2>Hello, {props.name}!</h2>;
    }
    
    // Class component:
    class Greeting extends React.Component {
      render() {
        return <h3>Greetings, {this.props.user}!</h3>;
      }
    }
    
    

    usage and rendering

    
    
    // Using the components:
    ReactDOM.render(
      <div>
        <WelcomeMessage name="Bob" />
        <Greeting user="Alice" />
      </div>,
      document.getElementById('root')
    );