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 - reactjs

I am having trouble on posting the lists of data in my table, I hope you guys can help me with this issue, this is the error i am getting Error: 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.
const columns = [
{
name: "name",
label: "Name",
options: {
filter: true,
sort: true,
}
},
{
name: "dateregistered",
label: "Date Registered",
options: {
filter: true,
sort: false,
}
},
{
name: "department",
label: "Department",
options: {
filter: true,
sort: false,
}
},
];
const data = [
posts.map(post => [{name: 'post.firstname', dateregistered: 'post.date', department: 'post.department'}])
];
return (
<>
<MUIDataTable
title={"Deactivated Users"}
data={data}
columns={columns}
options={options}
/>
</>
)

I see two problems in your data constant. The first one, the .map method returns an array, so there is no need to wrap that value inside an array keys []. The other problem is that you are wrapping the .map return state object in array keys too, that is why the error of creating an object is displayed, because you are returning arrays inside the main mapped array [[{ name: ... }], [{ name: ... }]].
So basically the solution for your issue would be:
const data = posts.map(post => ({name: 'post.firstname', dateregistered: 'post.date', department: 'post.department'}))
Where the parenthesis allows the map method to directly return the object.

The issue is that data is being created as an array in an array in an array. This is why when you try const data = posts.map(post => ...) the error persists, as there is still an array in an array. After you try the above, also re-write
post => [{name: 'post.firstname', dateregistered: 'post.date', department: 'post.department'}]
to
post => ({name: 'post.firstname', dateregistered: 'post.date', department: 'post.department'})
(Changing the square brackets to round)
P.S When you map over posts to build the data, you build a object with the the key "name" and the value "'post.firstname'". That value is a string literal and not accessing some other JS object (It will make "post.firstname" the value for all the post's. Same goes for the other keys.

Related

TanStack Table 8 : access nested array in data model

I'm looking for a way to access a nested array in my data structure.
My objects in my data array look like this :
{
name: name,
logo: url,
categories: [
{
name: Entertainment,
slug: "entertainment
},
{
name: Kids,
slug: kids
},
]
}
In the Docs I states that I need to use columnHelper.accessor to extract primitive values for each item in your data array.
My question is : how can I configure my accessor on "categories" to display both of them in my cell (using map I guess) ?
First, you don't need to use columnHelper; you can, for convenience (well, type safety, mostly).
You can do something like this:
cell: info => {
const value = info.getValue() as YourCategoryType[]; //casting may not be required here
return <>{value.map(v => <p key={v.slug}>{v.name}</p>)}</>
},

How to get prevState value or all object in useState in React?

In trek_tours i have an array and inside array i have define object and inside object their are some array and the format is in below
treks_tours[
{
title: "Everest Base Camp",
Prices: [
"Price Start from 300 per/person",
"Note - if you are number of people then we can make you good discount!",
],
},{
title: "Jungle Safare & Knowing Villager Life Style",
Prices: [
"Price Start from 1650 per/person",
"Note - if you are number of people then we can make you good discount!",
],
}
]
In this section i want to see the title and price name of differrent objects but i got repeted title same time. anyone please help me!!!
const [tripPrice, setTripPrice] = useState({});
const price = () => {
treks_tours.map((price) =>
setTripPrice((prevState) => ({
...prevState,
price: price.Prices[0].split(" ")[3],
title: price.title,
}))
);
};
console.log(tripPrice);
useEffect(() => {
price();
}, []);
Output
So from that array of objects, you want to individually console.log() all of them?
If so you want to individually console.log() all the objects all you have to do is:
trek_tours.forEach((tour) => {
console.log(tour);
})
And then it will console.log() every object in array. Is that what you mean?
If all you want to do is setTripPrice to array trek_tours
then all to do is to say setTripPrice(trek_tours) - no need of anything else.
Then if you console.log(tripPrice) you get all the objects inside the array. If this is not what you mean please provide a codesandbox link
{treks_tours.slice(0, 3).map((trek_tour, key) => {
<p className="text-lg text-black">
Starting from : $ {trek_tour.Prices[0].split(" ")[3]}
</p>
);
})}

Filter an Array through id and then mapping through a nested array inside

I'm stuck since a while trying to access a nested array inside another array after filtering it by an id. To be clear, this is the mock data I have:
bundleSets: [
{
id: 1,
title: "bundle set 1",
bundles: [
{
bundleTitle: "bundle 1",
content:[]
},
{
bundleTitle: "bundle 2",
content:[]
}
]
},
{ id:2,
title: "bundle set 2",
bundles: [
{bundleTitle: "ciaopao", content:[]}
]
},
{ id:3,
title: "bundle set 3",
bundles: [
{bundleTitle: "ciapo", content:[]}
]
}
]
Now I need to filter each bundleSets by id, and then access the bundles array inside and mapping those elements. This is what I tried to do:
const [key,setKey]=useState(1)
const [bundles,setBundles]=useState([])
useEffect(()=>{
const filteredBundles = bundleSets && bundleSets.filter(bundleSet=>bundleSet.id==key).map(filteredBundles=>{
return filteredBundles.bundles
})
setBundles(filteredBundles)
},[key])
Now If I try mapping the new state I can see on the console.log a weird [Array(1)] instead of the usual [{}] and I can't render it to the page. Where am I getting wrong with this?
Array.prototype.map returns an array and the callback you're passing to the map method returns filteredBundles.bundles which is an array. So, you get an array of arrays. filteredBundles is a confusing name, btw.
Since you're looking up the bundle by id and the ids are unique in the bundleSets array, you can use Array.prototype.find to find the bundle set by id and then get the bundle array. You can return an empty array if find returns undefined (if the key is not found).
const bundles = bundleSets?.find(set => set.id === key)?.bundles || []

how to call variable name in array of object in React

this is my code in react.
const [value, setValue] = React.useState<CountriesEntityData | null>({
id: '',
name: '',
regions: [
{
id: '',
name: '',
districts: [
{
id: '',
name: '',
locations: [{ id: '', city: '', division: '', street: '' }],
},
],
},
],
})
I try this code in resolving this problem
value?.regions?.name
can anyone give me tutorial link in dealing in this kind of situation thank you.
If you just wanna use the first element you can do:
let name = value?.regions?.[0]?.name;
If if you wanna search the object based on an id, then I think there is a find function on the array which you can use like that:
let name = value?.regions?.find((elm) => elm.id == 'myId')?.name;
a regions in value is array.
and not answer value?.regions?.name .
because regions contains objects and objects contain property ```name'''
for this kind of problems, simply you can use log and see your variable in console
console.log(your const);
then by looking at your console, easily you can see how to address your array to get your desired result.
Now assuming that you want to extract the nested names in the object,
for two arrays inside each other, you should use two MAP which are nested.
this can give you the idea:
{ListOfData.map((item, index) => (
<div key={index}>
<h1>{item.title}</h1>
{item.content.map((c, i) => (
<div key={i}>
<h3>{c.title}</h3>
<h3>{c.description}</h3>
<hr />
</div>
))}
</div>
))}

Can't access nested stateful objects in ReactJS

I am trying to access a nested object in ReactJS. This is what the object looks like:
const characteristics = [
{ id: "geo", content: 'Geopolitical' },
{ id: "dog", content: 'Dog Loving' },
];
const starterColumns = {
"1": {
name: 'I am',
items: characteristics
},
"2": {
name: 'fullstack developer',
items: []
}
}
const [columns, setColumns] = useState(starterColumns);
This is the error I get when I try to console.log(columns['2']['items']['0']['id']):
TypeError: Cannot read property 'id' of undefined
Does this have to do with the fact that I am working with a stateful variable? Is something funky going on with the nested objects? Thanks for the help!
EDIT
The problem was that there was no object in the column so I had no object to access. Now the problem outstanding is how do I fill that void without displaying a new drag and drop piece. Thanks for helping!
EDIT
I used a try/catch statement to check the object so if it is empty, nothing happens.
Use try catch only for errors that you can't handle
To access an element use dot notation whenever it's possible instead of using bracket notation []
When there is an empty array in the items you can't access to the id you will get an error so the solution is to check if the array is not empty
columns['2'].items.length > 0
To access the first element of an array you have to use [0] instead of ['0']
try this solution
if (columns['2'].items.length > 0) {
console.log(columns['2'].items[0].id)
}

Resources