← Back to Blog

React: Passing Information from Child to Parent while Mapping JSON Data

coding
web

By Kevin Hou

2 minute read

I've had a lot of issues in the past week trying to figure out how to pass information from the child component to the parent component while mapping JSON data.

Here's what it looks like to pass information from the child component to the parent component:

1module.exports = React.createClass({ 2 handleClick(number) { 3 ... // This runs when the child component clicks. Parent component now has access to Child component variable, 'number' 4 }, 5 render() { 6 return ( 7 <Child handleClick={this.handleClick} /> 8 ) 9 } 10}); 11 12const Child = React.createClass({ 13 render() { 14 return ( 15 <button onClick={this.props.handleClick.bind(this, number)}>Click me</button> 16 ) 17}); 18

Here's what it looks like to map a JSON object:

1var contactNodes = this.props.contacts.map(function (contact) { 2 var firstName = contact.firstName.toUpperCase(); 3 var lastName = contact.lastName.toUpperCase(); 4 var found = firstName.includes(str) + lastName.includes(str); 5 return ( 6 <h1>{firstName} {lastName}</h1> 7 ); 8 } 9}); 10

Unfortunately, it's difficult to combine these two things because when using this.handleClick, this refers to the current object it is in. When you map data, this refers to contactNodes, not the component; therefore, you cannot refer to a function while mapping JSON data. I finally figured out a simple way around this issue. Instead of including all my HTML in the return while mapping, I used the map function to set states. Then I passed those states into the components in the regular render() function. This allowed me to use functions because the this would refer to the correct object.

Example:

1module.exports = React.createClass({ 2 getInitialState() { 3 return { 4 str: this.props.data.map(function (data) { 5 return data.type; 6 }), 7 }; 8 }, 9 handleClick() { 10 console.log("Click"); 11 }, 12 render() { 13 return ( 14 <GameAnswerChoices 15 handleClick={this.handleClick} 16 string={this.state.str} 17 /> 18 ); 19 }, 20}); 21