Home > Software engineering >  Pass jsx as value in an object
Pass jsx as value in an object

Time:04-01

I want to pass jsx as a value for a key in an object. This is what I'm doing:

const getRightDiv = () => {
    return (
        <div>This is what I want to pass</div>
    );
}

var card = {
    title: "haha",
    subtitle: "yes",
    div: getRightDiv()
}

//In my Child Component
return (
    <div>
        { card.title === "haha" && card.div}
    </div>
);

But this isn't working. There is no error message, but the div doesn't render. How can I pass jsx in an object?

CodePudding user response:

I think you are not passing props correctly to your child component. I hope it will help you

 const getRightDiv = () => {
  return <div>This is what I want to pass </div>;
};
var card = {
  title: "haha",
  subtitle: "yes",
  div: getRightDiv(),
};
//In my Child Component
const ChildComponent = (props) => {
  return <div>{card.title === "haha" && props.card.div}</div>;
};

const ParentComponent = () => {
  return <ChildComponent card={card} />;
};
export default ParentComponent;

CodePudding user response:

I think it'll work

const GetRightDiv = () => {
    return (
        <div>This is what I want to pass</div>
    );
}

var card = {
    title: "haha",
    subtitle: "yes",
    div: <GetRightDiv/>
}

//In my Child Component
return (
    <div>
        { card.title === "haha" && props.card.div}
    </div>
);

you can pass props to GetRightDiv too if you want to.

  • Related