Home > Enterprise >  How to get all props from a component that is being passed as a prop?
How to get all props from a component that is being passed as a prop?

Time:11-21

I have this component called SpecialComp that is being passed as a prop to MyComp . My question is how to pass all of the props from SpecialComp (color, size, weight) to MyComp so then I can override the attributes set in MyComp? In other words how can I have access to SpecialComp’s props inside of MyComp?

<MyComp customcomp ={<SpecialComp color=‘green’ size=‘20’ weight=‘bold’/>} />

export const MyComp = ({customcomp}) => {
  return (
    <div>
    {React.cloneElement(customcomp, {color: ‘red’})}
    </div>
  );
}

CodePudding user response:

You can simply access the props by calling customcomp.props:

import React from "react";

const MyComp = ({ customcomp }) => {

  console.log(customcomp.props);
  //Prints: {color: "green", size: "20", weight: "bold"}

  return <div>{React.cloneElement(customcomp, { color: "red" })}</div>;
};

export default MyComp;

codeSandbox for this here.

CodePudding user response:

If you don't want to make use of any state management solution. Then you can consider lifting the state (prop) up. See code examples below:

import React from "react";

export const App = () => {
  const [specialProps, setSpecialProps] = useState({
    color: "green",
    size: "20",
    weight: "bold",
  }); // make the properties as state

  return (
    <MyComp
      customComponentStyles={specialProps} // you can pass it here
      customComponent={
        <SpecialComp
          color={specialProps.color} // you can pass it here too
          size={specialProps.size}
          weight={specialProps.weight}
        />
      }
    />
  );
};

export const MyComp = ({ customComponentStyles, customComponent }) => { // access the same prop here as well
  return <div>{React.cloneElement(customcomp, { color: "red" })}</div>;
};

CodePudding user response:

<MyComp customcomp ={<SpecialComp color=‘green’ size=‘20’ weight=‘bold’/>} />

export const MyComp = ({customcomp}) => {
  return (
    <div>
    {React.cloneElement(customcomp, {...customcomp.props,color: ‘red’})}
    </div>
  );
}
  • Related