React Components

#day2learningReact

React Components

Components are the most important core concepts of React using which we can build User Interfaces and can integrate them into other Components as well, enhancing the reusability.

Basic web page Structure:

Components in React:

Using React we can build each element as a separate component. Say for example:

A button can be created as a component.

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import reportWebVitals from './reportWebVitals';

const MyButton =() =>{
  return <div>MyButton</div>
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <MyButton/>
    <div>Hello World</div>
  </React.StrictMode>
);

'MyButton' is a local component created. This is rendered within the same file.

Essential conventions to be followed while creating components are:

  1. The name of the Component must always start with a capital letter. If not it will not be considered as a Component by React.

  2. If a Component returns more than one line then the return statements must be enclosed in the curved brackets other wise the remaining lines will not be rendered by the component importing that particular component.

     const MyButton() =>{
         return <div>Hello World</div>;
     }
    
     const Container=() =>{
         return(
             <div>
                 <h1>Card Title</h1>
                 <p>Description</p>
             </div>
         )};
     export default Container;
    

Here, Container is the name of the component and this can be rendered in another file as <Container/> .

To export the component "export default <Component name>" is used so that it can be used in any file that imports this component.