How to show a Javascript object in JSX?

How to use JSX in React.js? »

Let’s try to create a javascript object and print it’s values using JSX. Make the following changes in the index.js file:

// Import Libraries

import React from 'react';
import ReactDOM from 'react-dom';

// Create React Component and javascript object inside it

const App = function() {
const myObject = { name: "Gautam Kabiraj" }
return <div> <h1 style={{ color: 'red'}} > {myObject} </h1> </div> ;
};

// Show React Component on the browser
ReactDOM.render( <App/>, document.querySelector('#root') );

Right after saving the file, you’ll be greeted with an error that looks something like this:

Objects are not valid as a React child (found: object with keys {name}). If you meant to render a collection of children, use an array instead.

in h1 (at src/index.js:14)

in div (at src/index.js:13)

in App (at src/index.js:23)

It simple means that React cannot accept javascript (object)values directly and render it using JSX. What you need to do instead is, specify what values you want from within the javascript object. For instance, in the above code, React cannot access myObject object directly, but it can understand myObject.name. So, make the necessary changes and the error should go away:

// Import Libraries
import React from 'react';
import ReactDOM from 'react-dom';

// Create React Component and javascript object inside it
const App = function() {

const myObject = {
name: "Gautam Kabiraj"
}

return <div>
<h1 style={{ color: 'red'}} >
{myObject.name}
</h1>
</div>;

};

// Show React Component on the browser
ReactDOM.render(
<App/>,
document.querySelector('#root')
);

[/code]

Leave a Comment