Reputation: 33
import React from "react";
class App extends React.Component {
state = {
companies: [
{
name: "company1",
jobs: [
{
name: "job1-1",
salary: [{ junior: 1234 }, { senior: 2345 }, { mid: 34566 }]
},
{
name: "job1-2",
salary: [
{
junior: 9876
},
{
senior: 98777
},
{
mid: 34566
}
]
},
{
name: "job1-3",
salary: [
{
junior: 9446
},
{
senior: 98947
},
{
mid: 134566
}
]
}
]
},
{
name: "company2",
jobs: [
{
name: "job2-1",
salary: [
{ junior: 343431234 },
{ senior: 552345 },
{ mid: 4434566 }
]
},
{
name: "job2-2",
salary: [
{
junior: 99876
},
{
senior: 5698777
},
{
mid: 4434566
}
]
},
{
name: "job3-3",
salary: [
{
junior: 933446
},
{
senior: 9338947
},
{
mid: 13334566
}
]
}
]
}
],
selectedCompany: "company1",
selectedJob: "job1-1"
};
handleChange = e => {
this.setState({ selectedCompany: e.target.value });
};
handleChange2 = e => {
this.setState({ selectedJob: e.target.value });
};
render = () => {
let company = this.state.companies.filter(company => {
return company.name === this.state.selectedCompany;
});
return (
<div>
jobs
<select
value={this.state.selectedJob}
onChange={this.handleChange2.bind(this)}
>
{company[0].jobs.map((sal, i) => {
return <option>{sal.name}</option>;
})}
</select>
companies
<select
value={this.state.selectedCompany}
onChange={this.handleChange.bind(this)}
>
{this.state.companies.map((company, i) => {
return <option>{company.name}</option>;
})}
</select>
</div>
);
};
}
export default App;
What I have done is, there are 3 nested arrays inside the companies
array. jobs
inside companies
and salary
inside job
. The output looks like this: Output
The onChange handler of Company
works, it also changes the initial state of selectedCompany
to whichever I select using the handleChange event. The onChange triggers the Jobs
to change according to the selected Company.
Now, the question is how do I change the initial state of selectedJob too? I have made another handleChange2 for Job. If I explicitely select job, the selectedJob changes it's value but I need to make it work Just by the change in Company.
The react developer tool shows that selectedJob
value changes only if I manually select one.
In summary, change the state of selectedJob
by changing the state of Company.
Upvotes: 2
Views: 426
Reputation: 20755
If I understood your query correctly, then you want on change of company
, the first job from the selected company should get set as selectedJob
in state.
You can do like this,
handleChange = e => {
let company = this.state.companies.filter(company => {
return company.name === e.target.value;
});
let selectedJob = company[0].jobs[0].name; //This will get first job from selected company
this.setState({ selectedCompany: e.target.value, selectedJob }, ()=> console.log(this.state.selectedJob));
};
Note: You need to add key
when you iterate array
using .map
. See the warning you are getting and key
accordingly.
Upvotes: 1