Creating unique key props for array children (React.js) - javascript

I am trying to build out a component in React which takes information from a JSON source, and uses some of that information to create states which can be passed down into other separate components. While I haven't passed my states into separate components yet, I have been able to get my state to update with the information from the JSON. However, when I load my page I get an error code which I want to sort out before continuing with my project in case there are unintended side effects from leaving the error in my code. The error code reads as following:
index.js:1 Warning: Each child in a list should have a unique "key" prop.
Check the render method of FetchData
in div (at FetchData.js:27)
in FetchData (at App.js:8)
in div (at App.js:7)
My App.js looks like this:
import React from 'react';
import './App.css';
import FetchData from './Components/FetchData/FetchData';
function App() {
return (
<div className="App">
<FetchData/>
</div>
);
}
export default App;
My FetchData.js looks like this:
import React from 'react';
class FetchData extends React.Component {
constructor() {
super();
this.state = {
portrait: null,
title: null
};
}
componentDidMount() {
fetch('https://randomuser.me/api')
.then (response => {
return response.json();
})
.then (data => {
let userImage = data.results.map((person) => {
return (
<div>
<img alt='portrait' img src={person.picture.large}/>
</div>
)
})
let userTitle = data.results.map((person) => { //line 27
return (
<div key={person.results}>
<div> {person.name.title} </div>
</div>
)
})
this.setState ({
portrait: userImage,
title: userTitle
})
console.log(this.portrait, this.title)
})
}
render() {
return (
<div className='box1'>
<div className='box2'>
<h2>{this.state.title}</h2>
{this.state.portrait}
</div>
</div>
)
}
};
export default FetchData;
and just in case since my index.js looks like this:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
serviceWorker.unregister();
I thought the issue was the fact that I used "person" into both my "data.results.map" so I tried to change the naming but that did not work either. Any help would be greatly appreciated!

The error is referring to your FetchData component.
The reconciliation algorithm in React can work if you assign an unique key to returned DOM objects. In this case, you are returning from the map function a list of similar DOM object. Any returned chunk have to declare the key attribute on the parent node.
In your case:
componentDidMount() {
fetch('https://randomuser.me/api')
.then (response => {
return response.json();
})
.then (data => {
let userImage = data.results.map((person) => {
return (
<div key={person.id}>
<img alt='portrait' img src={person.picture.large}/>
</div>
)
})
let userTitle = data.results.map((person) => { //line 27
return (
<div key={person.id}>
<div> {person.name.title} </div>
</div>
)
})
this.setState ({
portrait: userImage,
title: userTitle
})
console.log(this.portrait, this.title)
})
}
The key value must be an unique string and it is used by React to update the correct DOM nodes on state change. (I don't know how your person.results is filled, but you need a sort of ID)
For simple component you can also use this syntax
let userImage = data.results.map((person,idx) => {
return (
<div key={idx}>
<img alt='portrait' img src={person.picture.large}/>
</div>
)
})
Be aware using this syntax, because idx is the position of the current element in the containing array, and if used more than one time, it results in duplicate keys (And React will think that nodes with same key are the same nodes)

Using Index as a key is an anti-pattern in React.
Never using the index as a key in React, unless:
the list and items are static–they are not computed and do not change
the items in the list have no ids;
the list is never reordered or filtered.
When all of them are met, you may safely use the index as a key.
If not, please use the unique ID.
It may come from the elements you are going to display,
Or you can add a new ID property to your model or hash some parts of the content to generate a key.
The key only has to be unique among its siblings, not globally unique.
Read more here and here in React Docs

In your data.results.map((person)) function you need to add idx prop, so your code should look like:
let userImage = data.results.map((person,idx) => {
return (
<div key={idx}>
<img alt='portrait' img src={person.picture.large}/>
</div>
)
})

You can simply add the key attribute in the elements whenever you are using .map
let userImage = data.results.map((person, index) => {
return (
<div key={index}>
<img alt='portrait' img src={person.picture.large}/>
</div>
)
})
For the value of the key, it is preferred to use an unique id. If you do not have one, you can use index instead.

Related

How to reRender the Page after Splice Method in reactJS?

After onClick method to splice array, data seems to delete but page isn't updating. How to reRender or update the page to reflect the changes?
Home.js:
import React from "react";
import "./HomeStyles.css";
import HomeData from "./HomeData";
function Home() {
function handleDelete(id) {
var index = HomeData.map(function (e) {
return e.id;
}).indexOf(id);
HomeData.splice(index, 1);
}
return (
<>
<section className="home_section">
<div className="home_container">
{HomeData.map((item) => {
return (
<div className="Heading_container" key={item.id}>
<h1 className="home_heading">{item.heading} </h1>
<button onClick={handleDelete}>Delete</button>
</div>
);
})}
<button className="submit_btn">Submit</button>
</div>
</section>
</>
);
}
export default Home;
Data:
const HomeData = [
{
id: 1,
heading: 'This is first Heading'
},
{
id: 2,
heading: 'This is Second Heading'
},
]
export default HomeData;
I have tried using useNavigate from react-router-dom and history, but it didn't work.
In React functional components you can use a hook called useState. With this hook you can get and set the data however you want it.
const [data, setData] = useState(homeData);
Mutating state however is a big no-no in the React ecosystem because of the fact that it heavily practices the concept of immutability. Splice mutates the state by deleting or adding to the element itself.
Instead of mapping and splicing you can use filter with the setter. Filter is immutable, because it creates a shallow copy. You want to create a shallow copy, but without the item that has the id given as a parameter in your function. This would translate to the following code:
setData(homeData.filter(home => home.id !== id));
Now all you have to do is map through the state "data" instead of the homeData directly.
Maybe you can utilize state for this, can use useState hooks
It will be something like this:
import React, {useState} from "react";
import "./HomeStyles.css";
import HomeData from "./HomeData";
function Home() {
const [data,setData] = useState(HomeData)
function handleDelete(id) {
const newData = data.filter((e) => e.id !== id)
setData(newData)
}
return (
<>
<section className="home_section">
<div className="home_container">
[don't forget to use the state here] >>> {data.map((item) => {
return (
<div className="Heading_container" key={item.id}>
<h1 className="home_heading">{item.heading} </h1>
<button onClick={handleDelete}>Delete</button>
</div>
);
})}
<button className="submit_btn">Submit</button>
</div>
</section>
</>
);
}
export default Home;
Issue
In the current implementation the code is mutating an object that ins't part of any React state, so React isn't aware that anything needs to be rerendered.
Things to keep in mind:
Array.prototype.splice does an in-place mutation of the array it operates over.
The splice() method changes the contents of an array by removing or
replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice().
React components rerender for one of three reasons:
A local component state update is enqueued, component and sub-ReactTree rerender
A passed props value is updated, component and sub-ReactTree rerender
The parent component rerendered (because state and/or props updated)
Solution
To correctly render and update the HomeData array it necessarily should be part of a React component state. When updating React state, all state, and sub-state, necessarily needs to be a new object reference. This is because React uses a shallow reference equality check. It's far more common to use Array.prototype.filter to filter an existing array and return a new array reference.
Home Example:
import React from "react";
import "./HomeStyles.css";
import HomeData from "./HomeData";
function Home() {
const [homeData, setHomeData] = React.useState(HomeData); // <-- initialize state
const handleDelete = (id) => {
setHomeData(data => data.filter(el => el.id !== id)); // <-- filter and return new array
};
return (
<section className="home_section">
<div className="home_container">
{homeData.map((item) => ( // <-- map homeData state
<div className="Heading_container" key={item.id}>
<h1 className="home_heading">{item.heading}</h1>
<button
button="button" // <-- should be explicit with button type
onClick={handleDelete}
>
Delete
</button>
</div>
))}
<button
className="submit_btn"
type="submit" // <-- should be explicit with button type
>
Submit
</button>
</div>
</section>
);
}
export default Home;
You should use the useState hooks to update the view
import React, { useState } from "react"; //imported useState
import "./HomeStyles.css";
import HomeData from "./HomeData";
function Home() {
const [homeData, setHomeData] = useState(HomeData); //Added here
function handleDelete(id) {
const newData = homeData.filter((e) => e.id !== id)
setHomeData(newData)
}
return (
<>
<section className="home_section">
<div className="home_container">
{homeData.map((item) => { //changed state here
return (
<div className="Heading_container" key={item.id}>
<h1 className="home_heading">{item.heading} </h1>
<button onClick={handleDelete}>Delete</button>
</div>
);
})}
<button className="submit_btn">Submit</button>
</div>
</section>
</>
);
}
export default Home;

Trouble accessing and displaying JSON using ReactJS and the fetch-api

everyone thanks for the help!
I have looked at several similar questions but have not been able to extrapolate their answers to solve my problem.
I am using a ReactJS application to consume JSON from a website. I'm using the code from https://pusher.com/tutorials/consume-restful-api-react and changing it to fit my situation.
Currently, when I view index.js, I get the error "TypeError:
assetList.assets is undefined." Given the the JSON and code below, what do I need to change to
display a list of the assets and their properties?
I would like something like the display to look like the Desired Display below.
Desired Display.
There are two 2 assets:<br/>
id: 1317 Filename: PROCESS_FLOW.pdf
id: 1836 Filename: 004527_FS.jpg
JSON consumed from website
{"totalNumberOfAssets":2,
"assets":[
{"id":"1317","attributes":{"Filename":["PROCESS_FLOW.pdf"]}},
{"id":"1836","attributes":{"Filename":["004527_FS.jpg"]}}
]}
components/assetList.js
import React from 'react'
const AssetList = ({assetList}) => {
return (
<div>
There are {assetList.totalNumberOfAssets} assets:
{assetList.assets.map((asset) => (
<div>
id: {asset.id} filename: {asset.filename}
</div>
))}
</div>
)
};
export default AssetList
App.js
import React, {Component} from 'react';
import AssetList from './components/assetList';
class App extends Component {
render() {
return (
<AssetList assetList={this.state.assetList} />
)
}
state = {
assetList: []
};
componentDidMount() {
fetch('http://ligitaddress/api/v1/asset')
.then(res => res.json())
.then((data) => {
this.setState({ assetList: data })
})
.catch(console.log)
}
}
export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
On your first render, the value of this.state.assetList is an array:
state = {
assetList: []
};
However you are passing it into <AssetList>
const AssetList = ({assetList}) => {
return (
<div>
There are {assetList.totalNumberOfAssets} assets:
{assetList.assets.map((asset) => (
<div>
id: {asset.id} filename: {asset.filename}
</div>
))}
</div>
)
};
The line saying assetList.assets.map is trying to call map() on something that is undefined. (you can access the property assets on an array and it will be undefined) It seems like it expects assetList to be an object with an assets array in it, but in your parent component assetList is initialized to an array... in short you're confusing yourself as to what kind of data you expect to be where.
Either change your initial state to reflect how you expect it to be passed into <AssetList>:
state = {
assetList: {
assets: []
}
};
And/or change your <AssetList> component to properly check its prop:
const AssetList = ({assetList}) => {
return (
<div>
There are {assetList.totalNumberOfAssets} assets:
{Array.isArray(assetList.assets) && assetList.assets.map((asset) => (
<div>
id: {asset.id} filename: {asset.filename}
</div>
))}
</div>
)
};
This is happening because your components/assetList.js is trying to access assetList.assets on assetList.assets.map without it being defined.
When the API request is made and has not returned yet, the assets on assetList have not being defined, since assetList on App.js is initialized to an empty array.
You can replace the line on components/assetList.js with assetList.assets && assetList.assets.map(...) and that should do it

ReactJS - Nothing was returned from render

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
I Have an issue related to this message. This is my component that causes the error:
import React from 'react';
import Thumbnail from './Thumbnail';
const AlbumList = ({ results }) => {
let collections = [];
let albums = { };
Object.values(results).map((item, i) => {
if(!collections.includes(item.collectionId)) {
collections.push(item.collectionId);
albums[i] = {id: item.collectionId, cover: item.artworkUrl100}
}
return albums;
});
Object.values(albums).forEach(element => {
return (
<Thumbnail source={element.cover} />
)
})
}
export default AlbumList;
Thumbnail is just a basic Component like:
import React from 'react';
const Thumbnail = ({source}) => {
return(
<div>
<img src={source} alt="album cover"/>
</div>
)
}
export default Thumbnail;
I've been looking for the error like an hour or so.
What am I missing?
Notice that map returns a list while forEach returns undefined.
You don't return anything from your functional Component Plus forEach does not return anything, instead change it to map.
Also you need to set the unique key to Thumbnail component in loop
return Object.values(albums).map((element, index) => {
return (
<Thumbnail key={"Key-"+index} source={element.cover} />
)
})
I would suggest to read this article map vs. forEach

Render child components with Enzymejs tests

I'm trying to test a simple component that take some props (it have no state, or redux connection) with Enzyme, it works for the plain elements like <div /> and so on, but when i try to test if the element rendered by the child component exists, it fails.
I'm trying to use mount but it spit me a lot of errors, i'm new in this so, here is my code:
import React, { Component } from 'react';
import WordCloud from 'react-d3-cloud';
class PredictWordCloud extends Component {
render() {
const fontSizeMapper = word => Math.log2(word.value) * 3.3;
const { size, data, show } = this.props;
if (!show)
return <h3 className='text-muted text-center'>No data</h3>
return (
<section id='predict-word-cloud'>
<div className='text-center'>
<WordCloud
data={data}
fontSizeMapper={fontSizeMapper}
width={size}
height={300} />
</div>
</section>
)
}
}
export default PredictWordCloud;
It's just a wrapper for <WordCloud />, and it just recieves 3 props directly from his parent: <PredictWordCloud data={wordcloud} size={cloudSize} show={wordcloud ? true : false} />, anything else.
The tests is very very simple for now:
import React from 'react';
import { shallow } from 'enzyme';
import PredictWordCloud from '../../components/PredictWordCloud.component';
import cloudData from '../../helpers/cloudData.json';
describe('<PredictWordCloud />', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<PredictWordCloud data={cloudData} size={600} show={true} />)
});
it('Render without problems', () => {
const selector = wrapper.find('#predict-word-cloud');
expect(selector.exists()).toBeTruthy();
});
});
For now it pass but if we change the selector to: const selector = wrapper.find('#predict-word-cloud svg'); where the svg tag is the return of <Wordcloud /> component, the tests fails because the assertion returns false.
I tried to use mount instead of shallow, exactly the same test, but i get a big error fomr react-d3-cloud:
PredictWordCloud Render without problems TypeError: Cannot read property 'getImageData' of null.
This is specially weird because it just happens in the test environment, the UI and all behaviors works perfectly in the browser.
You can find your component directly by Component name.
Then you can use find inside your sub-component as well.
e.g
it('Render without problems', () => {
const selector = wrapper.find('WordCloud').first();
expect(selector.find('svg')).to.have.length(1);
});
or
You can compare generated html structure as well via
it('Render without problems', () => {
const selector = wrapper.find('WordCloud').first();
expect(selector.html()).to.equal('<svg> Just an example </svg>');
});

Encountered two children with the same key

I'm really new to react and redux development. I have a list component that is connected to a container. I want to update a list on scroll but i get:
Encountered two children with the same key
My component:
import React, { Component, PropTypes } from 'react'
import Track from './Track'
import styles from './TrackList.css'
const altImg = require('../images/sc.jpg');
export default class TrackList extends Component {
static propTypes = {
tracks: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number.isRequired
}).isRequired).isRequired,
onTrackListScroll: PropTypes.func.isRequired
}
render() {
const { tracks, onTrackListScroll } = this.props;
return (
<div>
<ul className='tracks'
onScroll={(e)=>{
console.log('SCROLL!!',e)
onTrackListScroll()
}}>
{tracks.map(track =>
<Track
key={track.id}
{...track}
//onClick={() => onTrackClick(track.id)}
text={track.title}
imgSrc={!track.artwork_url ? altImg : track.artwork_url}
/>
)}
</ul>
</div>
)
}
}
reducer that update a state is :
const toSearchResultOb = (tracks) => {
return {
tracks: tracks
}
}
case 'UPDATE_SEARCH_RESULT':
return Object.assign({}, state,
toSearchResultOb(state.tracks.concat(action.tracks)))
What is correct way to update component onScroll with redux?
You're getting this error because keys between component siblings need to be unique. You probably have duplicate track.id in your tracks array.
Here's an easy fix:
{tracks.map(track, i =>
<Track
key={i}
{...track}
//onClick={() => onTrackClick(track.id)}
text={track.title}
imgSrc={!track.artwork_url ? altImg : track.artwork_url}
/>
)}
If you have a look at the documentation of map() on MDN, you'll see this:
callback Function that produces an element of the new Array, taking
three arguments:
currentValue The current element being processed in
the array.
index The index of the current element being processed in
the array.
So in the example above, i is the index of the current element. This index increments on each iteration which guarantees unique keys within that map(). Now you don't have to worry about what track.id is.

Categories