Combine two object keys in and array without loosing the value - javascript

I have an object that I'm mapping through its keys in my react component to display header titles.
obj1 = {
TERM_NOTE: 'TERM_NOTE',
EQUITY: 'EQUITY',
REVENUE_SHARING_NOTE: 'REVENUE_SHARING_NOTE',
CONVERTIBLE_NOTES: 'CONVERTIBLE_NOTES',
SAFE: 'SAFE',
FUNDS: 'FUNDS',
}
const keytermsSecurityTypes = Object.keys(obj1);
keytermsSecurityTypes.forEach((type) => {
listAsPerSecurityType[type] = props.investments.filter(i => get(i, 'offering.keyTerms.securities') === type);
listHeaderAsPerSecurityType[type] = listMetaByType.filter(i => i.securityType.includes('ALL') || i.securityType.includes(type));
});
and the variables mentioned before are used inside the React component:
keytermsSecurityTypes.map(type => (
<>
{listAsPerSecurityType[type] && listAsPerSecurityType[type].length
&& (
<>
<Header as="h5" className="investment-list" content={getSecurityHeaderTitle(type)} />
<ListTable listData={listAsPerSecurityType[type]} header={listHeaderAsPerSecurityType[type]}/>
</>
)}
</>
))
for CONVERTIBLE_NOTES and SAFE keys, title should display as "Convertible Securities" for both as one title. However I still need to keep the values of both keys as they are being used in the same component as well.
While I got the title to display the same string for both keys, I still can't figure out how to combine them into one title.
Also, considering I'm still new to React and javascript, is there a better way/best practice to do this?
Desired output:
Design spec
Problem output:
Problem
Thank you.

Related

TypeError: Cannot read properties of undefined (reading 'length')

Working my way through my first fullstack MERN app that allows a user to add multiple places to an array. Trying to map over the array to display the number of places for the user. Code works fine until I use .length, then it crashes.
import React from 'react';
import UserItem from './UserItem';
import Card from '../../shared/components/UIElements/Card/Card';
import './UsersList.css';
const UsersList = props => {
if (props.items.length === 0) {
return (
<div className="center">
<Card>
<h2>No users found.</h2>
</Card>
</div>
);
}
return (
<ul className="users-list">
{props.items.map(user => (
<UserItem
key={user.id}
id={user.id}
image={user.image}
name={user.name}
// placeCount={user.places.length}
placeCount={user.places}
/>
))}
</ul>
);
};
export default UsersList;
The full error stack:
Uncaught TypeError: Cannot read properties of undefined (reading 'length')
The above error occurred in the <UsersList> component:
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
I did a keyword search of .length throughout the backend and frontend files to double check the code and make sure I didn't have any typos anywhere--but for the life of me I can't figure out why adding .length isn't working.
I've gone through a few different posts on here but cannot find a working solution.
Any insight would be greatly appreciated. For now I just commented out .length so I can keep working. Thank you!
The other answers are focusing on prop.items list but in your question you mention that you get the exception when trying to access the length of the places inside users.
You are getting the error message because some users may not have any places listed inside them, hence, no places list -> no length property.
To fix this, you need to check if the places list exists and then access its length:
placeCount={ user.places ? user.places.length : 0 }
Here, we use a ternary operator to check if user.places exists, then we use the length, else use zero.
Edit:
As pointed out by Phil in the comments below, you can also use coalescing operator, which is much cleaner, like this:
placeCount={ user.places?.length ?? 0 }
The syntax simply translates as if user.places has a value for length, then use that value, else use zero as a default value.
You can define a default value for items to fix it.
const UsersList = ({ items = [] }) => {
if (items.length === 0) {
return (
...
);
}
return (
<ul className="users-list">
{items.map((user) => (
...
))}
</ul>
);
};
Changing this if condition from this:
if (props.items.length === 0) {
To
if (!props.items?.length) {
Should work.
Similarly if using for places,you can check using ternary operator if length exists in array of places.
How? Because items could possibly be null or undefined from apis, so the length property on array might be missing.
Moreover, using ! Not operator would make this condition true if length of items is 0 or is null or undefined or any falsy value
Here you can use object destructuring. if you are not sure whether the data will come or not.
JSX will always render first and after that props, so in some cases it may render empty JSX.
you can make the changes in your component like this
const UsersList = props => {
const { items = [] } = props
// checking whether its an array or not and have some items in it
if (!Array.isArray(items) || items.length === 0) {
return (
<div className="center">
<Card>
<h2>No users found.</h2>
</Card>
</div>
);
}
return (
<ul className="users-list">
{items.map(user => {
const { id = "", image = "", name = "", places = "" } = user
return <UserItem
key={id}
id={id}
image={image}
name={name}
// placeCount={user.places.length}
placeCount={places}
/>
})}
</ul>
);
};

React JS - Props is not shown in the rendered HTML [duplicate]

I'm building a React component that accepts a JSON data source and creates a sortable table.
Each of the dynamic data rows has a unique key assigned to it but I'm still getting an error of:
Each child in an array should have a unique "key" prop.
Check the render method of TableComponent.
My TableComponent render method returns:
<table>
<thead key="thead">
<TableHeader columns={columnNames}/>
</thead>
<tbody key="tbody">
{ rows }
</tbody>
</table>
The TableHeader component is a single row and also has a unique key assigned to it.
Each row in rows is built from a component with a unique key:
<TableRowItem key={item.id} data={item} columns={columnNames}/>
And the TableRowItem looks like this:
var TableRowItem = React.createClass({
render: function() {
var td = function() {
return this.props.columns.map(function(c) {
return <td key={this.props.data[c]}>{this.props.data[c]}</td>;
}, this);
}.bind(this);
return (
<tr>{ td(this.props.item) }</tr>
)
}
});
What is causing the unique key prop error?
You should add a key to each child as well as each element inside children.
This way React can handle the minimal DOM change.
In your code, each <TableRowItem key={item.id} data={item} columns={columnNames}/> is trying to render some children inside them without a key.
Check this example.
Try removing the key={i} from the <b></b> element inside the div's (and check the console).
In the sample, if we don't give a key to the <b> element and we want to update only the object.city, React needs to re-render the whole row vs just the element.
Here is the code:
const data = [
{ name: "Nuri", age: 28, city: "HO" },
{ name: "Talib", age: 82, city: "HN" },
{ name: "Jenny", age: 41, city: "IT" },
];
const ExampleComponent = React.createClass({
render: function () {
const infoData = this.props.info;
return (
<div>
{infoData.map((object, i) => {
return (
<div className={"row"} key={i}>
{[
object.name,
// remove the key
<b className="fosfo" key={i}>
{" "}
{object.city}{" "}
</b>,
object.age,
]}
</div>
);
})}
</div>
);
},
});
React.render(<ExampleComponent info={data} />, document.body);
The answer posted by #Chris at the bottom goes into much more detail than this answer.
React documentation on the importance of keys in reconciliation: Keys
Be careful when iterating over arrays!!
It is a common misconception that using the index of the element in the array is an acceptable way of suppressing the error you are probably familiar with:
Each child in an array should have a unique "key" prop.
However, in many cases it is not! This is anti-pattern that can in some situations lead to unwanted behavior.
Understanding the key prop
React uses the key prop to understand the component-to-DOM Element relation, which is then used for the reconciliation process. It is therefore very important that the key always remains unique, otherwise there is a good chance React will mix up the elements and mutate the incorrect one. It is also important that these keys remain static throughout all re-renders in order to maintain best performance.
That being said, one does not always need to apply the above, provided it is known that the array is completely static. However, applying best practices is encouraged whenever possible.
A React developer said in this GitHub issue:
key is not really about performance, it's more about identity (which in turn leads to better performance). randomly assigned and changing values are not identity
We can't realistically provide keys [automatically] without knowing how your data is modeled. I would suggest maybe using some sort of hashing function if you don't have ids
We already have internal keys when we use arrays, but they are the index in the array. When you insert a new element, those keys are wrong.
In short, a key should be:
Unique - A key cannot be identical to that of a sibling component.
Static - A key should not ever change between renders.
Using the key prop
As per the explanation above, carefully study the following samples and try to implement, when possible, the recommended approach.
Bad (Potentially)
<tbody>
{rows.map((row, i) => {
return <ObjectRow key={i} />;
})}
</tbody>
This is arguably the most common mistake seen when iterating over an array in React. This approach isn't technically "wrong", it's just... "dangerous" if you don't know what you are doing. If you are iterating through a static array then this is a perfectly valid approach (e.g. an array of links in your navigation menu). However, if you are adding, removing, reordering or filtering items, then you need to be careful. Take a look at this detailed explanation in the official documentation.
class MyApp extends React.Component {
constructor() {
super();
this.state = {
arr: ["Item 1"]
}
}
click = () => {
this.setState({
arr: ['Item ' + (this.state.arr.length+1)].concat(this.state.arr),
});
}
render() {
return(
<div>
<button onClick={this.click}>Add</button>
<ul>
{this.state.arr.map(
(item, i) => <Item key={i} text={"Item " + i}>{item + " "}</Item>
)}
</ul>
</div>
);
}
}
const Item = (props) => {
return (
<li>
<label>{props.children}</label>
<input value={props.text} />
</li>
);
}
ReactDOM.render(<MyApp />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
In this snippet we are using a non-static array and we are not restricting ourselves to using it as a stack. This is an unsafe approach (you'll see why). Note how as we add items to the beginning of the array (basically unshift), the value for each <input> remains in place. Why? Because the key doesn't uniquely identify each item.
In other words, at first Item 1 has key={0}. When we add the second item, the top item becomes Item 2, followed by Item 1 as the second item. However, now Item 1 has key={1} and not key={0} anymore. Instead, Item 2 now has key={0}!!
As such, React thinks the <input> elements have not changed, because the Item with key 0 is always at the top!
So why is this approach only sometimes bad?
This approach is only risky if the array is somehow filtered, rearranged, or items are added/removed. If it is always static, then it's perfectly safe to use. For example, a navigation menu like ["Home", "Products", "Contact us"] can safely be iterated through with this method because you'll probably never add new links or rearrange them.
In short, here's when you can safely use the index as key:
The array is static and will never change.
The array is never filtered (display a subset of the array).
The array is never reordered.
The array is used as a stack or LIFO (last in, first out). In other words, adding can only be done at the end of the array (i.e push), and only the last item can ever be removed (i.e pop).
Had we instead, in the snippet above, pushed the added item to the end of the array, the order for each existing item would always be correct.
Very bad
<tbody>
{rows.map((row) => {
return <ObjectRow key={Math.random()} />;
})}
</tbody>
While this approach will probably guarantee uniqueness of the keys, it will always force react to re-render each item in the list, even when this is not required. This a very bad solution as it greatly impacts performance. Not to mention that one cannot exclude the possibility of a key collision in the event that Math.random() produces the same number twice.
Unstable keys (like those produced by Math.random()) will cause many component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components.
Very good
<tbody>
{rows.map((row) => {
return <ObjectRow key={row.uniqueId} />;
})}
</tbody>
This is arguably the best approach because it uses a property that is unique for each item in the dataset. For example, if rows contains data fetched from a database, one could use the table's Primary Key (which typically is an auto-incrementing number).
The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys
Good
componentWillMount() {
let rows = this.props.rows.map(item => {
return {uid: SomeLibrary.generateUniqueID(), value: item};
});
}
...
<tbody>
{rows.map((row) => {
return <ObjectRow key={row.uid} />;
})}
</tbody>
This is also a good approach. If your dataset does not contain any data that guarantees uniqueness (e.g. an array of arbitrary numbers), there is a chance of a key collision. In such cases, it is best to manually generate a unique identifier for each item in the dataset before iterating over it. Preferably when mounting the component or when the dataset is received (e.g. from props or from an async API call), in order to do this only once, and not each time the component re-renders. There are already a handful of libraries out there that can provide you such keys. Here is one example: react-key-index.
This may or not help someone, but it might be a quick reference. This is also similar to all the answers presented above.
I have a lot of locations that generate list using the structure below:
return (
{myList.map(item => (
<>
<div class="some class">
{item.someProperty}
....
</div>
</>
)}
)
After a little trial and error (and some frustrations), adding a key property to the outermost block resolved it. Also, note that the <> tag is now replaced with the <div> tag now.
return (
{myList.map((item, index) => (
<div key={index}>
<div class="some class">
{item.someProperty}
....
</div>
</div>
)}
)
Of course, I've been naively using the iterating index (index) to populate the key value in the above example. Ideally, you'd use something which is unique to the list item.
Check: key = undef !!!
You got also the warn message:
Each child in a list should have a unique "key" prop.
if your code is complete right, but if on
<ObjectRow key={someValue} />
someValue is undefined!!! Please check this first. You can save hours.
Just add the unique key to the your Components
data.map((marker)=>{
return(
<YourComponents
key={data.id} // <----- unique key
/>
);
})
You should use a unique value for each children key of tbody where
the value cannot not be identical (same) to its sibling
should not change between renders
For example, the key value can be database id or UUID (Universal Unique Identifier).
Here the keys are handling manually:
<tbody>
{rows.map((row) => <ObjectRow key={row.uuid} />)}
</tbody>
You can also let React handle the keys using React.Children.toArray
<tbody>
{React.Children.toArray(rows.map((row) => <ObjectRow />))}
</tbody>
Here are the React docs that explain well using the Key property, the key should be defined at the parent component it should not be used inside the child component.React Docs
Warning: Each child in an array or iterator should have a unique "key" prop.
This is a warning as for array items which we are going to iterate over will need a unique resemblance.
React handles iterating component rendering as arrays.
Better way to resolve this is provide index on the array items you are going to iterate over.for example:
class UsersState extends Component
{
state = {
users: [
{name:"shashank", age:20},
{name:"vardan", age:30},
{name:"somya", age:40}
]
}
render()
{
return(
<div>
{
this.state.users.map((user, index)=>{
return <UserState key={index} age={user.age}>{user.name}</UserState>
})
}
</div>
)
}
index is React built-in props.
When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:
const todoItems = todos.map((todo, index) =>
// Only do this if items have no stable IDs
<li key={index}>
{todo.text}
</li>
);
Please refer to List and Keys - React
In ReactJS if you are rendering an array of elements you should have a unique key for each those elements. Normally those kinda situations are creating a list.
Example:
function List() {
const numbers = [0,1,2,3];
return (
<ul>{numbers.map((n) => <li> {n} </li>)}</ul>
);
}
ReactDOM.render(
<List />,
document.getElementById('root')
);
In the above example, it creates a dynamic list using li tag, so since li tag does not have a unique key it shows an error.
After fixed:
function List() {
const numbers = [0,1,2,3];
return (
<ul>{numbers.map((n) => <li key={n}> {n} </li>)}</ul>
);
}
ReactDOM.render(
<List />,
document.getElementById('root')
);
Alternative solution when use map when you don't have a unique key (this is not recommended by react eslint ):
function List() {
const numbers = [0,1,2,3,4,4];
return (
<ul>{numbers.map((n,i) => <li key={i}> {n} </li>)}</ul>
);
}
ReactDOM.render(
<List />,
document.getElementById('root')
);
Live example: https://codepen.io/spmsupun/pen/wvWdGwG
If we have array object data . then we map to show the data . and pass the unique id (key = {product.id} ) because browser can select the unique data.
example : [
{
"id": "1",
"name": "walton glass door",
"suplier": "walton group",
"price": "50000",
"quantity": "25",
"description":"Walton Refrigerator is the Best Refrigerator brand in bv
Bangladesh "
},
{
"id": "2",
"name": "walton glass door",
"suplier": "walton group",
"price": "40000",
"quantity": "5",
"description":"Walton Refrigerator is the Best Refrigerator brand in
Bangladesh "
},
}
now we are mapping the data and pass the unique id:
{
products.map(product => <product product={product} key={product.id}
</product>)
}
According to React docs, each row/item should have a unique key.
Keys help React identify which items have changed, are added, or are removed.
Personally, I prefer using the crypto interface to generate a random UUID:
(crypto is built-in in vanilla-js)
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li key={crypto.randomUUID()}>item {number}
</li>
);
Best solution of define unique key in react:
inside the map you initialized the name post then key define by key={post.id} or in my code you see i define the name item then i define key by key={item.id}:
<div className="container">
{posts.map(item =>(
<div className="card border-primary mb-3" key={item.id}>
<div className="card-header">{item.name}</div>
<div className="card-body" >
<h4 className="card-title">{item.username}</h4>
<p className="card-text">{item.email}</p>
</div>
</div>
))}
</div>
I was running into this error message because of <></> being returned for some items in the array when instead null needs to be returned.
I had a unique key, just had to pass it as a prop like this:
<CompName key={msg._id} message={msg} />
This page was helpful:
https://reactjs.org/docs/lists-and-keys.html#keys
In my case, set id to tag
<tbody key={i}>
The problem is solved.
A visual explanation.
The incorrect way key=index (of an array)
As you can see, label 3, label 2, and label 1 ALL got re-rendered (flashing in the Elements panel).
The correct way key=uniqueId
Only the top new element flashes (gets re-rendered).
This is a warning, But addressing this will make Reacts rendering much FASTER,
This is because React needs to uniquely identify each items in the list. Lets say if the state of an element of that list changes in Reacts Virtual DOM then React needs to figure out which element got changed and where in the DOM it needs to change so that browser DOM will be in sync with the Reacts Virtual DOM.
As a solution just introduce a key attribute to each li tag. This key should be a unique value to each element.
var TableRowItem = React.createClass({
render: function() {
var td = function() {
return this.props.columns.map(function(c, i) {
return <td key={i}>{this.props.data[c]}</td>;
}, this);
}.bind(this);
return (
<tr>{ td(this.props.item) }</tr>
)
}
});
This will sove the problem.
If you are getting error like :
> index.js:1 Warning: Each child in a list should have a unique "key" prop.
Check the render method of `Home`. See https://reactjs.org/link/warning-keys for more information.
Then Use inside map function like:
{classes.map((user, index) => (
<Card **key={user.id}**></Card>
))}`enter code here`
This is a simple example,I have used a react condition with && first then map, in the I have added the key the user id to be sure that it's unique
<tbody>
{users &&
users.map((user) => {
return <tr key={user._id}>
<td>{user.username}</td>
<td><input
name="isGoing"
type="checkbox"
checked={user.isEnabled}
onChange={handleInputChangeNew}/></td>
<td>{user.role.roleTitle} - {user.role.department.departmentName}</td>
{/*<td className="text-right">
<Button>
ACTION
</Button>
</td>*/}
</tr>
})
}
</tbody>
your key should be unique.like an unique id.And your code should be like this
<div>
{products.map(product => (
<Product key={product.id}>
</Product>
))}
</div>
I don't go with the detail explanation but key to this answer is "key"
just put the key attribute in your tag and ensure that every-time you iterate you give unique value to it
#ensure that key's value is not clashing with others
Example
<div>
{conversation.map(item => (
<div key={item.id } id={item.id}>
</div>
))}
</div>
where conversation is an array something like below :
const conversation = [{id:"unique"+0,label:"OPEN"},{id:"unique"+1,label:"RESOLVED"},{id:"unique"+2,label:"ARCHIVED"},
]
I think when working with tables (or in similar examples), creating a unique key should be passed to child component from the parent component for the sake of REUSABILITY.
Because if you are creating a table, that means you are passing data from the parent. If you assign key={row.name} maybe currently data has name property but if you want to use this table component somewhere else you assume that in each row of data that you have passed, you have name property.
Since the engineer will be preparing the data in the parent component, the engineer should create a key function based on the data.
const keyFunc = (student) => {
return student.id;
};
In this case engineer knows what data it is sending, it knows that each row has id property which is unique. Maybe in the different data set, the data set is stock prices and it does not have "id" property but "symbol"
const keyFunc = (stock) => {
return stock.symbol;
};
this keyFunc should be passed to the child component as a prop to guarantee the reusability and uniqueness.
The "Each child in a list should have a unique "key" prop." warning happens in React when you create a list of elements without the special key attribute. Keys must be assigned to each element in a loop to give stable identity to elements in React.
We can set the id property of the object as a unique key.
export default function App() {
const posts = [
{ id: 1, title: "First "},
{ id: 2, title: "Second" },
{ id: 3, title: "Third" }
];
return (
<div>
<ul>
{posts.map(value =>
<li key={value.id}>{value.title}</li>
)}
</ul>
</div>
);}
//simple way
//if u using ant design remove the empty fragment...
//worng ans---> change to following crt ans
export default function App() {
const posts = [
{ id: 1, title: "First "},
{ id: 2, title: "Second" },
{ id: 3, title: "Third" }
];
{fields.map((field,index)=>{
return(
<> //empty fragment
<Row key={index}>
<Col span={6}>hello</Col>
</Row>
</>
)
})}
//correct ans
//remove the empty fragments after solve this key.prop warning problem
export default function App() {
const posts = [
{ id: 1, title: "First "},
{ id: 2, title: "Second" },
{ id: 3, title: "Third" }
];
{fields.map((field,index)=>{
return(
<> //empty fragment
<Row key={index}>
<Col span={6}>hello</Col>
</Row>
</>
)
})}
I faced a similar problem but not exact. Tried every possible solution and couldn't get rid of that error
Each child in an array should have a unique "key" prop.
Then I tried opening it in a different local host. I don't know how, but it worked!
If you are struggling with this error Each child in a list should have a unique "key" prop.
Solve by declaring index value to the key attribute inside the rendering element.
App.js component
import Map1 from './Map1';
const arr = [1,2,3,4,5];
const App = () => {
return (
<>
<Map1 numb={arr} />
</>
)
}
export default App
Map.js component
const Map1 = (props) => {
let itemTwo = props.numb;
let itemlist = itemTwo.map((item,index) => <li key={index}>{item}</li>)
return (
<>
<ul>
<li style={liStyle}>{itemlist}</li>
</ul>
</>
)
}
export default Map1

Dynamic input value in React

So I have a fragment factory being passed into a Display component. The fragments have input elements. Inside Display I have an onChange handler that takes the value of the inputs and stores it in contentData[e.target.id]. This works, but switching which fragment is displayed erases their values and I'd rather it didn't. So I'm trying to set their value by passing in the state object to the factory. I'm doing it in this convoluted way to accomodate my testing framework. I need the fragments to be defined outside of any component and passed in to Display as props, and I need them all to share a state object.
My problem is setting the value. I can pass in the state object (contentData), but to make sure the value goes to the right key in the contentData data object I'm trying to hardcode it with the input's id. Except contentData doesn't exist where the fragments are defined, so I get an error about not being able to reference a particular key on an undefined dataObj.
I need to find a way to set the input values to contentData[e.target.id]. Thanks.
File where fragments are defined. Sadly not a component.
const fragments = (onChangeHandler, dataObj) => [
<Fragment key="1">
<input
type="text"
id="screen1_input1"
onChange={onChangeHandler}
value={dataObj['screen1_input1']} // this doesn't work
/>
one
</Fragment>,
<Fragment key="2">
<input
type="text"
id="screen2_input1"
onChange={onChangeHandler}
value={dataObj['screen2_input1']}
/>
two
</Fragment>
]
Display.js
const Display = ({ index, fragments }) => {
const [contentData, setContentData] = useState({})
const onChange = e => {
// set data
const newData = {
...contentData,
[e.target.id]: e.target.value
}
setContentData(newData)
};
return (
<Fragment>{fragments(onChange, contentData)[index]}</Fragment>
);
};
After conversing with you I decided to rework my response. The problem is mostly around the implementation others might provide in these arbitrary fragments.
You've said that you can define what props are passed in without restriction, that helps, what we need to do is take in these nodes that they pass in, and overwrite their onChange with ours, along with the value:
const RecursiveWrapper = props => {
const wrappedChildren = React.Children.map(
props.children,
child => {
if (child.props) {
return React.cloneElement(
child,
{
...child.props,
onChange: props.ids.includes(child.props.id) ? child.props.onChange ? (e) => {
child.props.onChange(e);
props.onChange(e);
} : props.onChange : child.props.onChange,
value: props.contentData[child.props.id] !== undefined ? props.contentData[child.props.id] : child.props.value,
},
child.props.children
? (
<RecursiveWrapper
ids={props.ids}
onChange={props.onChange}
contentData={props.contentData}
>
{child.props.children}
</RecursiveWrapper>
)
: undefined
)
}
return child
}
)
return (
<React.Fragment>
{wrappedChildren}
</React.Fragment>
)
}
const Display = ({ index, fragments, fragmentIDs }) => {
const [contentData, setContentData] = useState(fragmentIDs.reduce((acc, id) => ({
...acc, [id]: '' }), {}));
const onChange = e => {
setContentData({
...contentData,
[e.target.id]: e.target.value
})
};
const newChildren = fragments.map(fragment => <RecursiveWrapper onChange={onChange} ids={fragmentIDs} contentData={contentData}>{fragment}</RecursiveWrapper>);
return newChildren[index];
};
This code outlines the general idea. Here we are treating fragments like it is an array of nodes, not a function that produces them. Then we are taking fragments and mapping over it, and replacing the old nodes with nodes containing our desired props. Then we render them as planned.

React app - Load selected array in Material UI Table not rendering checks

So I have been working hard for days and searching on how to do this. I have a Material UI table in my React App. I want to load a table where if my user has entries in the selected array it will prerender the checks in the DOM. The selected array is populated with the entries I want but my table which uses a onClick I think needs an event to trigger the DOM to render the check. This is relevant part of my table body.
<TableBody>
{this.props.competitorData.map(competitor => {
const isSelected = this.props.isSelected(competitor.key);
return (
<TableRow
hover
onClick={() => this.props.handleClick(competitor)}
role="checkbox"
aria-checked={isSelected}
tabIndex={-1}
key={competitor.key}
selected={isSelected}
>
<TableCell padding="checkbox">
<Checkbox checked={isSelected} />
</TableCell>
I have a toggle that loads my table. It fills the selected the array with the subset of data I want trigger in componentWillMount. (it's 2 tables, tier1 and tier 2).
componentWillMount() {
this.renderChecks(this.props.team)
}
renderChecks(team) {
const { selected1 } = this.state;
const { selected2 } = this.state;
let newSelected1 = [];
let newSelected2 = [];
team.map(teammate => {
if (teammate.tier === "1") {
newSelected1 = newSelected1.concat(selected1, teammate.key)
} else if (teammate.tier === "2") {
newSelected2 = newSelected2.concat(selected2, teammate.key)
}
this.setState({ selected1: newSelected1 });
this.setState({ selected2: newSelected2 });
})
}
Essentially I need a way to render isSelected based of another list that is the smaller list (team is a subset of competitorData) that has the same keys. Ive tried so many things it's to many to list here. Im looking for help on what to do to make this work because nothing has worked and Im not sure what direction I should be going on in at this point. I've tried a lot of things that seem to cause instability in the render. Essentially I've tried to make the isSelected more state based but setting and resetting that state with inline functions like
{() => this.myFunctionThatUpdatesIsSelectedState(Key)}
These blow up in render. Sometimes cause an ugly infinite loop.
Update
Based on #Eld0w post below this does render my subset of checks.
checkKeys(val) {
return this.props.team.some(teammate => {
return val.key === teammate.competitorKey;
});
}
getCompetitors = () => {
const { competitorData, team } = this.props;
return competitorData.map(
value => ({
value,
isSelected: this.checkKeys(value)
})
)
}
Tables looks like this now.
<TableBody>
{this.getCompetitors().map(competitor => {
console.log('MYCOMPETITOR2::', competitor);
return (
<TableRow
hover
onClick={event => this.props.handleClick(event, competitor.value)}
role="checkbox"
aria-checked={competitor.isSelected}
tabIndex={-1}
key={competitor.value.key}
selected={competitor.isSelected}
>
<TableCell padding="checkbox">
<Checkbox checked={competitor.isSelected} />
</TableCell>
There is small issues I didn't see coming. Now my table renders only the preselected checks since im not using my previous isSelected function which was:
isSelected1 = key => this.state.selected1.indexOf(key) !== -1;
Basically i need to render the existing checks but maintain the standard isSelected function somewhere in the process as well. If I think of something or post anything about it I'll update here as well. Further input is obviously welcome.
I think i need to load my team into my selected array then run my standard isSelected function. But this is where I seem to run into trouble since that is state based. Render goes crazy on me.
Final Update
So it was late last night. I just needed to change the criterion to make this whole thing work. I load my team array in the local state selected array. Then performed isSelected property check on my competitor. Now it loads my preselected and the user can then edit selects in the table from that point.
Final Solution
Load the preselect team into the local selected state array.
componentWillMount() {
this.renderChecks(this.props.team);
}
I have tiered tables. That is just some business logic (not important here). teammate.competitorKey is the key I store that is same key as the larger table, which is competitorData. I need that to get the compares to work.
renderChecks(team) {
const { selected } = this.state;
let newSelected = [];
team.map(teammate => {
if (teammate.tier === '1') {
newSelected = newSelected.concat(selected, teammate.competitorKey)
this.setState({ selected: newSelected });
}
})
}
getCompetitor can now just verify the value key exist in the array using includes
getCompetitors = () => {
const { competitorData, team } = this.props;
console.log('THISSTATESELECTED:::', this.state.selected)
return competitorData.map(
value => ({
value,
isSelected: this.state.selected.includes(value.key)
})
)
}
And Final Table looks like
<TableBody>
{this.getCompetitors().map(competitor => {
return (
<TableRow
hover
onClick={event => this.handleClick(event, competitor.value)}
role="checkbox"
aria-checked={competitor.isSelected}
tabIndex={-1}
key={competitor.value.key}
selected={competitor.isSelected}
>
<TableCell padding="checkbox">
<Checkbox checked={competitor.isSelected} />
</TableCell>
I know this is a lot of writing but is spent a lot of time trying to get all this working. I hope it helps someone looking to do. I will look into making this more redux worth and possibly going the reselect route to optimize but for now im going to enjoy a working table for a day. Thank you again #Eld0w !!
So basically, you want to add an isSelected props to your competitors array depending on another array's values. Avoid using state, it's only props combinations.
The straightforward solution
Instead of mapping directly your competitor's array, map on a function returning an array.
getCompetitors = () => {
const { competitors, team } = this.props;
return competitors.map(
competitor => ({
...competitor,
isSelected: // criterion
})
)
}
Basically, what this does is destructuring the object and adding a new property isSelected thanks to the spread operator ... (ES6)
In your render then call this.getCompetitors().map(competitor => ...) instead of this.props.competitors.
Optimize this solution
You will want to use a plugin such as reselect to avoid any useless render operation.
const competitorSelector = createSelector(
props => props.competitors,
props => props.team,
(competitors, team) => competitors.map(
competitor => ({
...competitor,
isSelected: // criterion
})
)
)
and then use it like this in your render :
this.competitorSelector(this.props)
You will also need to use competitor.isSelected instead of isSelected since the property is now part of your competitor's properties.

Understanding unique keys for array children in React.js

I'm building a React component that accepts a JSON data source and creates a sortable table.
Each of the dynamic data rows has a unique key assigned to it but I'm still getting an error of:
Each child in an array should have a unique "key" prop.
Check the render method of TableComponent.
My TableComponent render method returns:
<table>
<thead key="thead">
<TableHeader columns={columnNames}/>
</thead>
<tbody key="tbody">
{ rows }
</tbody>
</table>
The TableHeader component is a single row and also has a unique key assigned to it.
Each row in rows is built from a component with a unique key:
<TableRowItem key={item.id} data={item} columns={columnNames}/>
And the TableRowItem looks like this:
var TableRowItem = React.createClass({
render: function() {
var td = function() {
return this.props.columns.map(function(c) {
return <td key={this.props.data[c]}>{this.props.data[c]}</td>;
}, this);
}.bind(this);
return (
<tr>{ td(this.props.item) }</tr>
)
}
});
What is causing the unique key prop error?
You should add a key to each child as well as each element inside children.
This way React can handle the minimal DOM change.
In your code, each <TableRowItem key={item.id} data={item} columns={columnNames}/> is trying to render some children inside them without a key.
Check this example.
Try removing the key={i} from the <b></b> element inside the div's (and check the console).
In the sample, if we don't give a key to the <b> element and we want to update only the object.city, React needs to re-render the whole row vs just the element.
Here is the code:
const data = [
{ name: "Nuri", age: 28, city: "HO" },
{ name: "Talib", age: 82, city: "HN" },
{ name: "Jenny", age: 41, city: "IT" },
];
const ExampleComponent = React.createClass({
render: function () {
const infoData = this.props.info;
return (
<div>
{infoData.map((object, i) => {
return (
<div className={"row"} key={i}>
{[
object.name,
// remove the key
<b className="fosfo" key={i}>
{" "}
{object.city}{" "}
</b>,
object.age,
]}
</div>
);
})}
</div>
);
},
});
React.render(<ExampleComponent info={data} />, document.body);
The answer posted by #Chris at the bottom goes into much more detail than this answer.
React documentation on the importance of keys in reconciliation: Keys
Be careful when iterating over arrays!!
It is a common misconception that using the index of the element in the array is an acceptable way of suppressing the error you are probably familiar with:
Each child in an array should have a unique "key" prop.
However, in many cases it is not! This is anti-pattern that can in some situations lead to unwanted behavior.
Understanding the key prop
React uses the key prop to understand the component-to-DOM Element relation, which is then used for the reconciliation process. It is therefore very important that the key always remains unique, otherwise there is a good chance React will mix up the elements and mutate the incorrect one. It is also important that these keys remain static throughout all re-renders in order to maintain best performance.
That being said, one does not always need to apply the above, provided it is known that the array is completely static. However, applying best practices is encouraged whenever possible.
A React developer said in this GitHub issue:
key is not really about performance, it's more about identity (which in turn leads to better performance). randomly assigned and changing values are not identity
We can't realistically provide keys [automatically] without knowing how your data is modeled. I would suggest maybe using some sort of hashing function if you don't have ids
We already have internal keys when we use arrays, but they are the index in the array. When you insert a new element, those keys are wrong.
In short, a key should be:
Unique - A key cannot be identical to that of a sibling component.
Static - A key should not ever change between renders.
Using the key prop
As per the explanation above, carefully study the following samples and try to implement, when possible, the recommended approach.
Bad (Potentially)
<tbody>
{rows.map((row, i) => {
return <ObjectRow key={i} />;
})}
</tbody>
This is arguably the most common mistake seen when iterating over an array in React. This approach isn't technically "wrong", it's just... "dangerous" if you don't know what you are doing. If you are iterating through a static array then this is a perfectly valid approach (e.g. an array of links in your navigation menu). However, if you are adding, removing, reordering or filtering items, then you need to be careful. Take a look at this detailed explanation in the official documentation.
class MyApp extends React.Component {
constructor() {
super();
this.state = {
arr: ["Item 1"]
}
}
click = () => {
this.setState({
arr: ['Item ' + (this.state.arr.length+1)].concat(this.state.arr),
});
}
render() {
return(
<div>
<button onClick={this.click}>Add</button>
<ul>
{this.state.arr.map(
(item, i) => <Item key={i} text={"Item " + i}>{item + " "}</Item>
)}
</ul>
</div>
);
}
}
const Item = (props) => {
return (
<li>
<label>{props.children}</label>
<input value={props.text} />
</li>
);
}
ReactDOM.render(<MyApp />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
In this snippet we are using a non-static array and we are not restricting ourselves to using it as a stack. This is an unsafe approach (you'll see why). Note how as we add items to the beginning of the array (basically unshift), the value for each <input> remains in place. Why? Because the key doesn't uniquely identify each item.
In other words, at first Item 1 has key={0}. When we add the second item, the top item becomes Item 2, followed by Item 1 as the second item. However, now Item 1 has key={1} and not key={0} anymore. Instead, Item 2 now has key={0}!!
As such, React thinks the <input> elements have not changed, because the Item with key 0 is always at the top!
So why is this approach only sometimes bad?
This approach is only risky if the array is somehow filtered, rearranged, or items are added/removed. If it is always static, then it's perfectly safe to use. For example, a navigation menu like ["Home", "Products", "Contact us"] can safely be iterated through with this method because you'll probably never add new links or rearrange them.
In short, here's when you can safely use the index as key:
The array is static and will never change.
The array is never filtered (display a subset of the array).
The array is never reordered.
The array is used as a stack or LIFO (last in, first out). In other words, adding can only be done at the end of the array (i.e push), and only the last item can ever be removed (i.e pop).
Had we instead, in the snippet above, pushed the added item to the end of the array, the order for each existing item would always be correct.
Very bad
<tbody>
{rows.map((row) => {
return <ObjectRow key={Math.random()} />;
})}
</tbody>
While this approach will probably guarantee uniqueness of the keys, it will always force react to re-render each item in the list, even when this is not required. This a very bad solution as it greatly impacts performance. Not to mention that one cannot exclude the possibility of a key collision in the event that Math.random() produces the same number twice.
Unstable keys (like those produced by Math.random()) will cause many component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components.
Very good
<tbody>
{rows.map((row) => {
return <ObjectRow key={row.uniqueId} />;
})}
</tbody>
This is arguably the best approach because it uses a property that is unique for each item in the dataset. For example, if rows contains data fetched from a database, one could use the table's Primary Key (which typically is an auto-incrementing number).
The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys
Good
componentWillMount() {
let rows = this.props.rows.map(item => {
return {uid: SomeLibrary.generateUniqueID(), value: item};
});
}
...
<tbody>
{rows.map((row) => {
return <ObjectRow key={row.uid} />;
})}
</tbody>
This is also a good approach. If your dataset does not contain any data that guarantees uniqueness (e.g. an array of arbitrary numbers), there is a chance of a key collision. In such cases, it is best to manually generate a unique identifier for each item in the dataset before iterating over it. Preferably when mounting the component or when the dataset is received (e.g. from props or from an async API call), in order to do this only once, and not each time the component re-renders. There are already a handful of libraries out there that can provide you such keys. Here is one example: react-key-index.
This may or not help someone, but it might be a quick reference. This is also similar to all the answers presented above.
I have a lot of locations that generate list using the structure below:
return (
{myList.map(item => (
<>
<div class="some class">
{item.someProperty}
....
</div>
</>
)}
)
After a little trial and error (and some frustrations), adding a key property to the outermost block resolved it. Also, note that the <> tag is now replaced with the <div> tag now.
return (
{myList.map((item, index) => (
<div key={index}>
<div class="some class">
{item.someProperty}
....
</div>
</div>
)}
)
Of course, I've been naively using the iterating index (index) to populate the key value in the above example. Ideally, you'd use something which is unique to the list item.
Check: key = undef !!!
You got also the warn message:
Each child in a list should have a unique "key" prop.
if your code is complete right, but if on
<ObjectRow key={someValue} />
someValue is undefined!!! Please check this first. You can save hours.
Just add the unique key to the your Components
data.map((marker)=>{
return(
<YourComponents
key={data.id} // <----- unique key
/>
);
})
You should use a unique value for each children key of tbody where
the value cannot not be identical (same) to its sibling
should not change between renders
For example, the key value can be database id or UUID (Universal Unique Identifier).
Here the keys are handling manually:
<tbody>
{rows.map((row) => <ObjectRow key={row.uuid} />)}
</tbody>
You can also let React handle the keys using React.Children.toArray
<tbody>
{React.Children.toArray(rows.map((row) => <ObjectRow />))}
</tbody>
Here are the React docs that explain well using the Key property, the key should be defined at the parent component it should not be used inside the child component.React Docs
Warning: Each child in an array or iterator should have a unique "key" prop.
This is a warning as for array items which we are going to iterate over will need a unique resemblance.
React handles iterating component rendering as arrays.
Better way to resolve this is provide index on the array items you are going to iterate over.for example:
class UsersState extends Component
{
state = {
users: [
{name:"shashank", age:20},
{name:"vardan", age:30},
{name:"somya", age:40}
]
}
render()
{
return(
<div>
{
this.state.users.map((user, index)=>{
return <UserState key={index} age={user.age}>{user.name}</UserState>
})
}
</div>
)
}
index is React built-in props.
When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:
const todoItems = todos.map((todo, index) =>
// Only do this if items have no stable IDs
<li key={index}>
{todo.text}
</li>
);
Please refer to List and Keys - React
In ReactJS if you are rendering an array of elements you should have a unique key for each those elements. Normally those kinda situations are creating a list.
Example:
function List() {
const numbers = [0,1,2,3];
return (
<ul>{numbers.map((n) => <li> {n} </li>)}</ul>
);
}
ReactDOM.render(
<List />,
document.getElementById('root')
);
In the above example, it creates a dynamic list using li tag, so since li tag does not have a unique key it shows an error.
After fixed:
function List() {
const numbers = [0,1,2,3];
return (
<ul>{numbers.map((n) => <li key={n}> {n} </li>)}</ul>
);
}
ReactDOM.render(
<List />,
document.getElementById('root')
);
Alternative solution when use map when you don't have a unique key (this is not recommended by react eslint ):
function List() {
const numbers = [0,1,2,3,4,4];
return (
<ul>{numbers.map((n,i) => <li key={i}> {n} </li>)}</ul>
);
}
ReactDOM.render(
<List />,
document.getElementById('root')
);
Live example: https://codepen.io/spmsupun/pen/wvWdGwG
If we have array object data . then we map to show the data . and pass the unique id (key = {product.id} ) because browser can select the unique data.
example : [
{
"id": "1",
"name": "walton glass door",
"suplier": "walton group",
"price": "50000",
"quantity": "25",
"description":"Walton Refrigerator is the Best Refrigerator brand in bv
Bangladesh "
},
{
"id": "2",
"name": "walton glass door",
"suplier": "walton group",
"price": "40000",
"quantity": "5",
"description":"Walton Refrigerator is the Best Refrigerator brand in
Bangladesh "
},
}
now we are mapping the data and pass the unique id:
{
products.map(product => <product product={product} key={product.id}
</product>)
}
According to React docs, each row/item should have a unique key.
Keys help React identify which items have changed, are added, or are removed.
Personally, I prefer using the crypto interface to generate a random UUID:
(crypto is built-in in vanilla-js)
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li key={crypto.randomUUID()}>item {number}
</li>
);
Best solution of define unique key in react:
inside the map you initialized the name post then key define by key={post.id} or in my code you see i define the name item then i define key by key={item.id}:
<div className="container">
{posts.map(item =>(
<div className="card border-primary mb-3" key={item.id}>
<div className="card-header">{item.name}</div>
<div className="card-body" >
<h4 className="card-title">{item.username}</h4>
<p className="card-text">{item.email}</p>
</div>
</div>
))}
</div>
I was running into this error message because of <></> being returned for some items in the array when instead null needs to be returned.
I had a unique key, just had to pass it as a prop like this:
<CompName key={msg._id} message={msg} />
This page was helpful:
https://reactjs.org/docs/lists-and-keys.html#keys
In my case, set id to tag
<tbody key={i}>
The problem is solved.
A visual explanation.
The incorrect way key=index (of an array)
As you can see, label 3, label 2, and label 1 ALL got re-rendered (flashing in the Elements panel).
The correct way key=uniqueId
Only the top new element flashes (gets re-rendered).
This is a warning, But addressing this will make Reacts rendering much FASTER,
This is because React needs to uniquely identify each items in the list. Lets say if the state of an element of that list changes in Reacts Virtual DOM then React needs to figure out which element got changed and where in the DOM it needs to change so that browser DOM will be in sync with the Reacts Virtual DOM.
As a solution just introduce a key attribute to each li tag. This key should be a unique value to each element.
var TableRowItem = React.createClass({
render: function() {
var td = function() {
return this.props.columns.map(function(c, i) {
return <td key={i}>{this.props.data[c]}</td>;
}, this);
}.bind(this);
return (
<tr>{ td(this.props.item) }</tr>
)
}
});
This will sove the problem.
If you are getting error like :
> index.js:1 Warning: Each child in a list should have a unique "key" prop.
Check the render method of `Home`. See https://reactjs.org/link/warning-keys for more information.
Then Use inside map function like:
{classes.map((user, index) => (
<Card **key={user.id}**></Card>
))}`enter code here`
This is a simple example,I have used a react condition with && first then map, in the I have added the key the user id to be sure that it's unique
<tbody>
{users &&
users.map((user) => {
return <tr key={user._id}>
<td>{user.username}</td>
<td><input
name="isGoing"
type="checkbox"
checked={user.isEnabled}
onChange={handleInputChangeNew}/></td>
<td>{user.role.roleTitle} - {user.role.department.departmentName}</td>
{/*<td className="text-right">
<Button>
ACTION
</Button>
</td>*/}
</tr>
})
}
</tbody>
your key should be unique.like an unique id.And your code should be like this
<div>
{products.map(product => (
<Product key={product.id}>
</Product>
))}
</div>
I don't go with the detail explanation but key to this answer is "key"
just put the key attribute in your tag and ensure that every-time you iterate you give unique value to it
#ensure that key's value is not clashing with others
Example
<div>
{conversation.map(item => (
<div key={item.id } id={item.id}>
</div>
))}
</div>
where conversation is an array something like below :
const conversation = [{id:"unique"+0,label:"OPEN"},{id:"unique"+1,label:"RESOLVED"},{id:"unique"+2,label:"ARCHIVED"},
]
I think when working with tables (or in similar examples), creating a unique key should be passed to child component from the parent component for the sake of REUSABILITY.
Because if you are creating a table, that means you are passing data from the parent. If you assign key={row.name} maybe currently data has name property but if you want to use this table component somewhere else you assume that in each row of data that you have passed, you have name property.
Since the engineer will be preparing the data in the parent component, the engineer should create a key function based on the data.
const keyFunc = (student) => {
return student.id;
};
In this case engineer knows what data it is sending, it knows that each row has id property which is unique. Maybe in the different data set, the data set is stock prices and it does not have "id" property but "symbol"
const keyFunc = (stock) => {
return stock.symbol;
};
this keyFunc should be passed to the child component as a prop to guarantee the reusability and uniqueness.
The "Each child in a list should have a unique "key" prop." warning happens in React when you create a list of elements without the special key attribute. Keys must be assigned to each element in a loop to give stable identity to elements in React.
We can set the id property of the object as a unique key.
export default function App() {
const posts = [
{ id: 1, title: "First "},
{ id: 2, title: "Second" },
{ id: 3, title: "Third" }
];
return (
<div>
<ul>
{posts.map(value =>
<li key={value.id}>{value.title}</li>
)}
</ul>
</div>
);}
//simple way
//if u using ant design remove the empty fragment...
//worng ans---> change to following crt ans
export default function App() {
const posts = [
{ id: 1, title: "First "},
{ id: 2, title: "Second" },
{ id: 3, title: "Third" }
];
{fields.map((field,index)=>{
return(
<> //empty fragment
<Row key={index}>
<Col span={6}>hello</Col>
</Row>
</>
)
})}
//correct ans
//remove the empty fragments after solve this key.prop warning problem
export default function App() {
const posts = [
{ id: 1, title: "First "},
{ id: 2, title: "Second" },
{ id: 3, title: "Third" }
];
{fields.map((field,index)=>{
return(
<> //empty fragment
<Row key={index}>
<Col span={6}>hello</Col>
</Row>
</>
)
})}
I faced a similar problem but not exact. Tried every possible solution and couldn't get rid of that error
Each child in an array should have a unique "key" prop.
Then I tried opening it in a different local host. I don't know how, but it worked!
If you are struggling with this error Each child in a list should have a unique "key" prop.
Solve by declaring index value to the key attribute inside the rendering element.
App.js component
import Map1 from './Map1';
const arr = [1,2,3,4,5];
const App = () => {
return (
<>
<Map1 numb={arr} />
</>
)
}
export default App
Map.js component
const Map1 = (props) => {
let itemTwo = props.numb;
let itemlist = itemTwo.map((item,index) => <li key={index}>{item}</li>)
return (
<>
<ul>
<li style={liStyle}>{itemlist}</li>
</ul>
</>
)
}
export default Map1

Categories

Resources