InfiniteDev InfiniteDev - 10 days ago 6
React JSX Question

In React.js array value is not passing properly via props?

I have a react app that has two components one Customer and another called Tags. The Customer sends its state's tags value to Tags. As following:

Customer.jsx

import React from "react";
import Tags from "./Tags.jsx";

export default class Customer extends React.Component {
constructor(props) {
super(props);
this.state = {customer:''};
}
componentDidMount(){
const url = `http://localhost:3000/api/customers/${this.props.params.id}`
fetch(url)
.then(res=>res.json())
.then(data=>{
console.log(data);
this.setState({
customer: data
});
})
.catch(error=>{
console.log(error)
});
}
render() {
return (
<div>
Company Name :{this.state.customer.companyName}
Customer Name :{this.state.customer.name}
Tags: <Tags tags={this.state.customer.tags} />
</div>
);
}
}


Tags.jsx

import React from "react";

export default class Tags extends React.Component {
constructor(props) {
super(props);
}
render() {
let tags = this.props.tags.map(tag=>{
return (<span>tag</span>);
});
return (
<div>
{tags}
</div>
);
}
}


When I run the code I get, "TypeError: Cannot read property 'map' of undefined(…)". If I replace below from Tags.jsx

let tags = this.props.tags.map(tag=>{
return (<span>tag</span>);
});


with

console.log(this.props.tags);


The output is an array.
What is happening? I really do not understand. What can I do?

Answer

In the constructor of Customer you are defining the state of a customer as a string, not an object. You should change it to reflect the actual customer properties, ie:

 this.state = {customer: {name: '', tags: []}};