Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How should I pass a string as props to a React component?

I have a String component, which renders a title:

const String = (someString) => {
  return (
    <h1>{someString}</h1>
  )
}

const App = () => {
  const someString = 'abc'
  return (
    <String someString={someString}/>
  )
}

export default App;

However this errors out, throwing Objects are not valid as a React child. I can get around this by modifying the String component like so:

const String = (someString) => {
  return (
    <h1>{someString.someString}</h1>
  )
}

I’m confused why someString evaluates as an object in React. I can confirm it’s an object by console.logging someString in the first String component, where I see:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{someString: 'hello world'}

Is this the correct way I should pass a primitive string as props, via string.string? From reading through some articles, I thought I should be able to simply pass string.

https://www.g2i.co/blog/understanding-the-objects-are-not-valid-as-a-react-child-error-in-react

>Solution :

It looks like you need to add curly brackets in your String component declaration like this.

Try this:

const String = ({someString}) => { //this line needs curly brackets
   return (
      <h1>{someString}</h1>
   )
 }

const App = () => {
const someString = 'abc'
   return (
      <String someString={someString}/>
   )
 }

export default App;

Without those brackets your are referencing the whole prop object

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading