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:
{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