In the following code I need set text for a <li> html element to bold when variable isActive is true otherwise text should be rendered in plain.
Currently I receive the following 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 or wrap the object using createFragment(object) from the React add-ons. Check the render method of
Navigation
How to fix it?
import React from 'react'
const idSuffix = 'navigation__'
const Navigation = ({ onClick, id, title, tooltip, isActive }) => (
<li id={`${idSuffix}${id}`} onClick={onClick} alt={tooltip} data-active={isActive}>
{isActive ? <b>{title}</b> : {title} }
</li>
)
export default Navigation
1 Answer 1
Remove the curly braces from title:
const Navigation = ({ onClick, id, title, tooltip, isActive }) => (
<li id={`${idSuffix}${id}`} onClick={onClick} alt={tooltip} data-active={isActive}>
{isActive ? <b>{title}</b> : title }
</li>
);
If isActive === true, the <li> element will contain a JSX element with the title string wrapped in <b> elements, otherwise it will just contain the title string, which is OK.
When you put braces around the title, you are actually defining an object { title: title }, which is not acceptable by the React renderer.
The confusion comes from the different meaning of the curly braces in the scope of JSX code and plain JavaScript code. In JSX code, they are used to inject a variable's value in an element.
${idSuffix}${id}} onClick={onClick} alt={tooltip} data-active={isActive}> {title} </li>{isActive ? <b>{title}</b> : title}, better use className for that