Reputation: 68
I am new to reactjs. I am showing the json data in the table. I also want to display only specific table row data for the specific filter option. Here I want when noida is selected then the table should display only 2 nd 3rd row of the table. when Moradabad is selected the it should display only first row of the table.
Here I am attaching the image which displays all the rows , please help me in this filtration logic show only on selected city.
The code is below
import React from 'react';
import './style.css';
export default class JsonDataDisplay extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{
id: 1,
name: 'Akshit',
city: 'Moradabad',
},
{
id: 2,
name: 'Nikita',
city: 'Noida',
},
{
id: 3,
name: 'Deeksha',
city: 'Noida',
}
],
};
}
render() {
const displaydata = this.state.data.map((info) => (
<tr>
<td>{info.id}</td>
<td>{info.name}</td>
<td>{info.city}</td>
</tr>
));
return (
<>
<FilterComponent />
<br />
<section>
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>city</th>
</tr>
</thead>
<tbody>{displaydata}</tbody>
</table>
</section>
</>
);
}
}
function FilterComponent(props) {
const data = ['All', 'Noida', 'Moradabad'];
return (
<div>
<div>city</div>
<select>
{data.map((field) => (
<option>{field}</option>
))}
</select>
</div>
);
}
Upvotes: 1
Views: 2786
Reputation: 13235
Few more things to do,
selectedCity
state this.state = {
data: [
...
...
],
selectedCity: "All"
};
setSelectedCity = (selectedCity) => {
this.setState({ selectedCity });
};
displaydata
as belowconst displaydata = this.state.data
.filter(
({ city }) =>
this.state.selectedCity === "All" || this.state.selectedCity === city
)
.map((info) => (
<tr>
<td>{info.id}</td>
<td>{info.name}</td>
<td>{info.city}</td>
</tr>
));
setSelectedCity
as a prop to FilterComponent
<FilterComponent setSelectedCity={this.setSelectedCity} />
FilterComponent
to set the selectedCity
when selection changes.function FilterComponent({ setSelectedCity }) {
const data = ["All", "Noida", "Moradabad"];
return (
<div>
<div>city</div>
<select onChange={(e) => setSelectedCity(e.target.value)}>
{data.map((field) => (
<option value={field}>{field}</option>
))}
</select>
</div>
);
}
Upvotes: 2