Blog>
Snippets

Passing Data to Child Components Using Props

Show how to pass data from a parent component to a child component using props for displaying user details.
// ParentComponent.js - This is the parent component
import React from 'react';
import ChildComponent from './ChildComponent';

class ParentComponent extends React.Component {
  render() {
    const userDetails = {
      name: 'John Doe',
      age: 30,
      email: 'johndoe@example.com'
    };

    return (
      <div>
        {/* Passing the userDetails object to the ChildComponent as a prop */}
        <ChildComponent user={userDetails} />
      </div>
    );
  }
}

export default ParentComponent;
This is the ParentComponent where the userDetails object is defined and passed down to the ChildComponent via props.
// ChildComponent.js - This is the child component
import React from 'react';

class ChildComponent extends React.Component {
  render() {
    // Accessing the user prop passed from the parent component
    const { name, age, email } = this.props.user;

    return (
      <div>
        <p>Name: {name}</p>
        <p>Age: {age}</p>
        <p>Email: {email}</p>
      </div>
    );
  }
}

export default ChildComponent;
This is the ChildComponent which receives the userDetails through props and displays the user's info.