dev_el
dev_el

Reputation: 2947

Cannot render component when sending object property via props

Everything works below

const test = {
  title: "test title"
};

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <p>{test.title}</p>
    </div>
  );
}

But if I try to render a Test component that receives title props from test.title like below

const test = {
  title: "test title"
};

const Test = (title) => {
  return (
    <article>
      <h4>{title}</h4>
    </article>
  );
};

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <p>{test.title}</p>
      <Test title={test.title} />
    </div>
  );
}

I get the error

Objects are not valid as a React child (found: object with keys {title}). If you meant to render a collection of children, use an array instead.

What am I doing wrong?

Upvotes: 0

Views: 42

Answers (3)

Amar singh
Amar singh

Reputation: 13

when try to send props as an Object one should destruct the object or directly use props.title

Upvotes: 0

DecPK
DecPK

Reputation: 25408

You are embedding title which is an object in expression that's why it shows

Objects are not valid as a React child (found: object with keys {title}). If you meant to render a collection of children, use an array instead.

You can either destructure title or directly use props.title in the JSX

codesandbox

const Test = (props) => {
  return (
    <article>
      <h4>{props.title}</h4>
    </article>
  );
};

or

const Test = ({ title }) => {
  return (
    <article>
      <h4>{ title }</h4>
    </article>
  );
};

Upvotes: 2

Nikita Mazur
Nikita Mazur

Reputation: 1785

Props are passed as object into component, so your title is in props.title

const Test = (props) => {
 return (
    <article>
      <h4>{props.title}</h4>
    </article>)};

Upvotes: 1

Related Questions