ccprp
ccprp

Reputation: 1

Pass prop from parent to child in React

I have the following page:

import ParentComponent from '../components/ParentComponent';
import ChildComponent from '../components/ChildComponent';

const Page = () => {
  return (
    <ParentComponent color="white">
      <ChildComponent />
    </ParentComponent>
  );

}

export default Page;

Is there a way to access the color prop on the ParentComponent from inside the ChildComponent so I can manipulate some things based on if it's set to 'white'?

I haven't tried anything yet, please help!

Upvotes: 0

Views: 70

Answers (3)

nong tran
nong tran

Reputation: 11

You can use Context in React. Context provides a way to pass data through the component tree without having to pass props down manually at every level.

More information

Upvotes: 1

coglialoro
coglialoro

Reputation: 773

In your parent component you can clone your children and add a property to them like this:

  {React.Children.map(children, (child) => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, { color });
    }
  })}

Demo: https://stackblitz.com/edit/react-6p9qfb?file=src%2FApp.js

More info: How to pass props to {this.props.children}

Upvotes: 0

Chun
Chun

Reputation: 487

How about using a state to store the color and pass it to both components?

import React, { useState } from 'react';
import ParentComponent from '../components/ParentComponent';
import ChildComponent from '../components/ChildComponent';

const Page = () => {
  const [color, setColor] = useState('white')
  return (
    <ParentComponent color={color}>
      <ChildComponent color={color} />
    </ParentComponent>
  );

}

export default Page;

Upvotes: 0

Related Questions