Reputation: 157
I want to display a list of elements I have in Json.
json is for example:
[{"res": "1030-1130"},{"res": "1200-1400"},{"res": "1800-1930"}]
my code is :
render () {
const items = this.state.JsonList.map(item => <li>{item.res}</li> );
return (
<div>
<ul>
{items}
</ul>
</div>
But I have the error TypeError: Cannot read property 'map' of null
But if I make a console.log of this.state.JsonList it is not empty and returns:
0: {res: "1030-1130"} 1: {res: "1200-1400"} 2: {res: "1800-1930"}
Do you know how to solve it ?
Upvotes: 1
Views: 853
Reputation: 1850
you can use a reduce function as well instead of map
'var jsonlist= [{"res": "1030-1130"},{"res": "1200-1400"},{"res": "1800-1930"}];
function appendlist(total, num) {
return total + '<li>' + num.res + '</li><br>';
}
function render(item) {
return jsonlist.reduce(appendlist);
}'
Upvotes: 0
Reputation: 14385
You need to fix your example:
render () {
// never use upper case to store an array, try to change that as earliest as possible
const { JsonList: jsonList } = this.state;
const items = jsonList.map((item) => <li key={item.res}>{item.res}</li> );
return (
<div>
<ul>
{items}
</ul>
</div>
);
}
map
is a method of array
, if you doubt that your value is an array, you can do as follow:
const items = [...jsonList].map(item => <li key={item.res}>{item.res}</li>);
The console.log
seems to show that it is not an array, try also to log it's type
console.log(jsonList instanceof Array); // should return true
console.log(typeof jsonList); // should be array not a string
If it's a string, don't forget to JSON.parse
:
JSON.parse(jsonList).map((item) => <li key={item.res}>{item.res}</li>);
In the end, if your value is null
during initialization of your component, you can do:
const { JsonList: jsonList = [] } = this.state;
// or instead doing this in render, do it during state initialization
Note that TypeError: Cannot read property 'map' of null
is an explicit error when we try to access .map
on null
.
Upvotes: 1
Reputation: 692
you are facing this issue because this.state.JsonList is null during the render method call, to solve this
render() {
const { JsonList: jsonList = [] } = this.state; // if the jsonList is empty it will have default empty array value, hence null value error will not occur
const items = jsonList.map(item => <li>{item.res}</li> );
return (
<div>
<ul>
{items}
</ul>
</div>
);
}
hope this helps!!
Upvotes: 1