To fix Invariant Violation: Objects are not valid as a React child error, we should make sure we put items in the braces that can be rendered.
For instance, we write
const Comp = () => {
return (
<>
<p>{"foo"}</p>
<p>{1}</p>
<p>{null}</p>
</>
);
};
to render 'foo'
, 1 and null
in the p elements.
null
will render nothing.
And the other values will be displayed on the screen.
Objects can’t be rendered directly on the screen, so we’ve to convert them to strings with JSON.stringify
if we want to show them on the screen.
For instance, we write
const Comp = () => {
return (
<>
<p>{JSON.stringify({ foo: "bar" })}</p>
</>
);
};
to call JSON.stringify
to convert { foo: "bar" }
to a JSON string so they can be rendered.