I have a React component. It loads a local JSON file. In the constructor I want to loop through the local JSON file, find an item that matches a URL parameter, and set some state values. Here is my code so far:
import React,{Component} from "react";
import topics from './topics.json';
class Tutorial extends Component {
constructor(props){
super(props);
topics.map((topic, index) => {
if(topic.url === this.props.match.params.url)
{
this.state = {
url: this.props.match.params.url,
name: topic.name
};
}
})
}
render() {
return (
<div className="Tutorial">
<div className="ca-nav-spacer w3-hide-small"></div>
{this.state.name}
{this.state.url}
</div>
);
}
}
export default Tutorial;
I keep getting this error: Array.prototype.map() expects a return value from arrow function.
Must the map function return a value? If I'm not returning a value should I just use a for loop? Can I return the block of JSON and then set the state after the map? What would be the proper way to do this?
Edit: Changed page to topic
forEachor something instead ofmap, but I don't think this use case should use either. A better way to do it would be to use afindarray method to get the one matchingtopicand then just set the state once.pagevariable here? I don't see it declared anywhere.topic.page.url