Home > Back-end >  Is it possible to pass a component as a prop within an object using the spread operator?
Is it possible to pass a component as a prop within an object using the spread operator?

Time:02-08

Based on the official React documentation, I know that you can pass components as props to other components, in this manner:

function SplitPane(props) {
  return (
    <div className="SplitPane">
      <div className="SplitPane-left">
        {props.left}
      </div>
      <div className="SplitPane-right">
        {props.right}
      </div>
    </div>
  );
}

function App() {
  return (
    <SplitPane
      left={
        <Contacts />
      }
      right={
        <Chat />
      } />
  );
}

My question is, can you pass them within an object, using the spread (...) operator?

Something more like this, based on the above example? I'm just guessing at the syntax here.

const splitPaneProps = {
  left: {<Contacts />}
  right: {<Chat />}
}

return (<SplitPane {...splitPaneProps} />);

I've searched many combinations of "component", "props", "object" and "spread" with no luck, so this question is a last resort before I assume it's not a thing you can do or I'm really bad at searching.

CodePudding user response:

Yes, you just need to change the way you're creating that object:

const splitPaneProps = {
  left: <Contacts />,
  right: <Chat />
}

Curly brackets are used in the middle of JSX to pop you back into plain javascript, but since you're already in plain javascript, there's no need.

  •  Tags:  
  • Related