klondike
klondike

Reputation: 413

issue passing props in React

I'm experiencing a little confusion when it comes to passing props in react.

So if I have a component like such:

Example 1:
export default function App() {
  return (
    <div>
      <Component1 prop1={{name: "Cameron}} />
      <p>Start editing to see some magic happen :)</p>
    </div>
  );
}

That works fine, but then why doesn't this work:

Example 2:
export default function App() {
  return (
    <div>
      <Component1 {{name: "Cameron"}} />
      <p>Start editing to see some magic happen :)</p>
    </div>
  );
}

I get an error saying "expected '...'"

Then this works:

Example 3:
export default function App() {
  const nameObj = { name: 'Cameron'};
  return (
    <div>
      <Component1 {...nameObj} />
      <p>Start editing to see some magic happen :)</p>
    </div>
  );
}

But this doesn't:

Example 4:
export default function App() {
  return (
    <div>
      <Component1 {name: Cameron} />
      <p>Start editing to see some magic happen :)</p>
    </div>
  );
}

Aren't example 3 and example 4 essentially equivalent?

Sincerely, confused.

Upvotes: 0

Views: 33

Answers (1)

Nick Carbone
Nick Carbone

Reputation: 218

<Component propName={propValue} /> <- this is the correct syntax

In Example 1, you are passing a prop whose name is prop1 and whose value is an object {name: "Cameron"}. This works.

In Example 2, you are trying to pass an object without naming the prop. This won't work.

In Example 3, you are spreading the nameObj which will be the equivalent of:

<Component1 name='Cameron' />

This works as intended, although note the difference between this and Example 1.

In Example 4, you are again trying to pass an unnamed object. This won't work.

Upvotes: 1

Related Questions