1

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
2
  • I can confirm title is a string, and if use the following component is rendered properly <li id={${idSuffix}${id}} onClick={onClick} alt={tooltip} data-active={isActive}> {title} </li> Commented Apr 22, 2017 at 8:37
  • {isActive ? <b>{title}</b> : title}, better use className for that Commented Apr 22, 2017 at 8:48

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

ok it works, but why I should remove the braces from the second title?
Because it is already wrapped in braces, and wrapping it second times makes react rendering engine to consider it as an object.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.