Reputation: 55
render() {
const Array = this.props.students.map((data) => {
return (
<button
key={data.name}
//key={data.birthDate}
//key={data.age}
//key={data.class}
>{data.name}</button>
);
});
return (
<div>
{Array}
<StudentInfo name = {"Amira"}/>
</div>
);
}
This is my code. Currently I'm trying to pass array data from that <button></button>
into <StudentInfo />
and replace the name = {"Amira"}
Can anyone help me with this?
Thank you.
Upvotes: 0
Views: 10061
Reputation: 347
What you want to do is something like this
constructor(props){
super(props);
this.students = [
{name: 'john'},
{name: 'paul'},
{name: 'clara'}
];
this.state = {
selectedStudent: this.students[0]
}
this.selectStudent = this.selectStudent.bind(this);
}
selectStudent(student){
this.setState({selectedStudent: student});
}
render(){
return (
<div>
{this.students.map((student, i) => (
<button key={i}
onClick={() => this.selectStudent(student)}
>{student.name}</button>
))}
<h1>{this.state.selectedStudent.name}</h1>
</div>
);
}
online demo: https://codesandbox.io/s/91wp5j33pw
Upvotes: 0
Reputation: 1750
Doing this will solve the issue,
render() {
const nameArray = [];
const Array = this.props.students.map((data) => {
nameArray.push(data.name); //fill the array with names
return (
<button
key={data.name}
//key={data.birthDate}
//key={data.age}
//key={data.class}
>{data.name}</button>
);
});
return (
<div>
{Array}
<StudentInfo name = {nameArray}/>
</div>
);
}
Upvotes: 1
Reputation: 2065
this might be your answer: How to pass an array of items in REACT.js
Upvotes: 1