Props in React

Props in React

Table of contents

Props

  1. In React class components, you can pass props from a parent component to a child component by setting them as properties of the child component instance in the parent component's render method. Here's an example:

     // Parent component
     class ParentComponent extends React.Component {
       render() {
         const message = "Hello, world!";
         return (
           <ChildComponent message={message} />
         );
       }
     }
    
     // Child component
     class ChildComponent extends React.Component {
       render() {
         return (
           <div>{this.props.message}</div>
         );
       }
     }
    
  2. In this example, the parent component ParentComponent sets the message prop with the value "Hello, world!" and passes it to the child component ChildComponent by rendering it with the message prop as a property of the child component instance.

  3. The child component accesses the message prop through its props object in the render method and displays it in a div element.

  4. In React, props are passed down to components as JavaScript objects. When you pass a prop to a component, React creates a new object to represent the props and sets the prop values as properties of that object.

    example:

     <ChildComponent name="John" age={25} />
    
  5. Here, we're passing two props to the ChildComponent component: name and age.

  6. React creates a new object to represent these props, which might look something like this:

     {
       name: "John",
       age: 25
     }
    
  7. This object is then passed as a single argument to the ChildComponent function when it's rendered. Within the component, we can access the prop values using the props object.

  8. React also has built-in mechanisms for handling default props and type-checking for props using PropTypes.

  9. These can help ensure that your components receive the correct props and handle them appropriately.