How to Render an Array of Objects in React

How to render an array of objects in React?

You can do it in two ways:

First:

render() {
const data =[{"name":"test1"},{"name":"test2"}];
const listItems = data.map((d) => <li key={d.name}>{d.name}</li>);

return (
<div>
{listItems }
</div>
);
}

Second: Directly write the map function in the return

render() {
const data =[{"name":"test1"},{"name":"test2"}];
return (
<div>
{data.map(function(d, idx){
return (<li key={idx}>{d.name}</li>)
})}
</div>
);
}

How to iterate and extract single objects from an array of objects to render in React

You’re right that you can do this more efficiently. You only need to map once. You can use a fragment to encase the multiple elements, this fragment is never rendered but allows you to have multiple children.

shortArray.map((data, index) => (
<React.Fragment key={index}>
<div>{data.time}</div>
<div>{data.weather}</div>
// anything else you want rendered
<React.Fragment />
));

There’s no need for you to map this array multiple times.

Just a side note, fragments that don't need keys can be written as empty tags in JSX:

<> /** React fragment code here */ </>

React state management rendering for one object or array of objects

Part 1:

As per the following definition:
React schedules a render every time the state of a component changes.
useState changes only the component where change occurs.
In your case, I believe, the re-render occurs.

Why re-invent the wheel when it's already invented?

If you are concerned about forms, you should explore this library:
https://react-hook-form.com/

Also, you will be able to properly visualize it in the section Isolate Re-renders of https://react-hook-form.com/

Part 2:

You can use useState to store an Array and that Array can be a set of Objects.

In order to render components from the Array, you can further use map function.

Or if you want to simply access the data, then you can use index values to access objects.

I hope, this makes sense.

Explanation could have been better if the whole code snippet for your concerns was shared.

Regards,
Shameel Uddin

How to render random object from array in React?

Your useEffect() callback runs after the initial render (not before). So on the first render randomData.key2 will be undefined, so you can't call .map() on it. You have a few options to fix this, but the most appropriate is to remove the useEffect() and set the data to a random value when you first call useState():

const getRandomObject = (array) => {
const randomObject = array[Math.floor(Math.random() * array.length)];
return randomObject;
};

const MyComponent = () => {
const [randomData, setRandomData] = useState(() => getRandomObject(DATA));

return (
...
);
}

See working example below:

const { useState } = React;

const DATA = [
{
key1: 'value1',
key2: ['string1', 'string2', 'string3']
},
{
key1: 'value2',
key2: ['string4', 'string5', 'string6']
},
{
key1: 'value3',
key2: ['string7', 'string8', 'string9']
}
];

const getRandomObject = (array) => {
const randomObject = array[Math.floor(Math.random() * array.length)];
return randomObject;
};

const MyComponent = () => {
const [randomData, setRandomData] = useState(() => getRandomObject(DATA));

return (
<div>
<h2>{randomData.key1}</h2>
{randomData.key2.map((item) => (
<div>
<input type='checkbox' id={item} value={item} />
<label htmlFor={item}>{item}</label>
</div>
))}
</div>
);
}

ReactDOM.render(<MyComponent />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>

Sort & render an array of objects using a select in ReactJS

Lots of issues as pointed by David. You need to use state to manage the users & update state whenever sort direction is changed in the select. It's pretty straight forward. Working sample -

const {useState} = React;

function App() {
const [users, setUsers] = useState([
{ id: 1, name: "One" },
{ id: 2, name: "Two" },
{ id: 3, name: "Three" }
]);
function onSelectionChange(e) {
const sortDirection = e.target.value;
const copyArray = [...users]; // create a new array & not mutate state

copyArray.sort((a, b) => {
return sortDirection === "0" ? a.id - b.id : b.id - a.id;
});
setUsers(copyArray); //re-render
}

return (
<div className="App">
<select defaultValue={0} onChange={onSelectionChange}>
<option value={0}>Ascending</option>
<option value={1}>Descending</option>
</select>
{users.map((user) => (
<div key={user.id}>
{user.id} - {user.name}
</div>
))}
</div>
);
}

ReactDOM.render(
<App/>,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react">

how can i render array of objects with react

You’ve embedded a bare {comments} in your render function right before the ternary; comments is an object and can’t be dropped into the DOM raw, just like the error message is telling you.

Remove that line and it should be fine.

Render values from array of objects which contains an object (React, Typescript)

You can try something like this, target is an array, map it's objects inside, get the key and value of each object.

Use the key to set it in data-profile-id while the value holds another object which contains names and dob. Map the array of names to get all the names inside the array.

targets.map( target => {
const [key, value] = Object.entries( target )[0]
return (
<div>
{
value.names?.map( name =>
<>
<input data-profile-id={key} data-key="names" type="checkbox" />
<label>{name}</label>
</>
)
}
</div>
)
} )


Related Topics



Leave a reply



Submit