Props in ReactJS

#day4learningReact

Introduction:

The concept of Props is used in React for allowing a parent component to communicate with its child component by passing the information through Props. These are needed to pass the values dynamically to a component. Props are similar to HTML tag attributes and allow any kind of JavaScript values like String, number, object, and function.

Let us understand how props are implemented. Suppose we have a parent component 'Todo' and a child component 'TodoItem'. An example where we are not passing any props to the child component.

import React from "react";
import "./styles.css";
import TodoItem from "./TodoItem";

export const Todo =()=> {
  return (
    <div >
      <Todo />
      <Todo />
      <Todo />
      <Todo />
    </div>
  );
}

Passing the props through a component:

  1. Passing props from a parent component <Todo>

    We are passing a string to its child component and this can be read by <TodoItem/>.

     import React from "react";
     import "./styles.css";
     import TodoItem from "./TodoItem";
    
     export const Todo =()=> {
       return (
         <div>
           <TodoItem title="Coding"/>
           <TodoItem title="Coding"/>
           <TodoItem title="Coding"/>
           <TodoItem title="Repeat"/>
         </div>
       );
     }
    
  2. Reading the props in child component </TodoItem>

    The props can be read by either using the props object or by destructuring the object which can be mentioned in { }.

     import React from "react";
    
     export const TodoList= (props)=>{
       return(
         <div>
           <li>{props.title}</li>
       </div>
       )
     }
    

    or we can also read props by using the object destructuring concept of javascript.

     import React from "react";
    
     export const TodoList= ({title})=>{
       return(
         <div>
           <li>{title}</li>
       </div>
       )
     }
    
  3. The following is the result of dynamically passed values in an <li> of the child component.

This is the simplest example of passing the props in React. Similarly we can pass objects, arrays as props to a child component.