Objective:
For Value 1, the CSS class should be badge-primary
For Value 2, the CSS class should be badge-secondary
For all other values, use the CSS class badge-danger
This functionality is implemented in the handleChange function.
Issue:
Currently, I can only toggle between false and true to apply CSS. This limits me to only two options.
How can I introduce a third option and resolve this issue? Any suggestions?
Details:
*New to reactjs
Stackblitz:
https://stackblitz.com/edit/react-34tdvs?
CSS Styles
h1,
p {
font-family: Lato;
}
.badge-primary {
text-align: center;
color: blue;
}
.badge-danger {
font-size: 15px;
color: red;
}
.badge-secondary {
font-size: 15px;
color: rgb(0, 204, 255);
}
import React from 'react';
import './style.css';
import React, { Component } from 'react';
import axios from 'axios';
export default class App extends Component {
constructor() {
super();
this.state = {
isLoaded: false,
listData: [],
list2Data: [],
list3DataRaw: [],
list3Data: [],
value: true
};
}
componentDidMount() {
axios
.get('https://jsonplaceholder.typicode.com/comments?postId=1')
.then(response =>
this.setState({
isLoaded: true,
listData: response.data
})
);
axios.get('https://jsonplaceholder.typicode.com/users').then(response =>
this.setState({
isLoaded: true,
list2Data: response.data
})
);
axios.get('https://jsonplaceholder.typicode.com/todos').then(response =>
this.setState({
isLoaded: true,
list3DataRaw: response.data
})
);
}
handleChange = ({ target }) => {
// copy current list of items
const list = [...this.state.list3DataRaw];
if (1 == target.value) {
this.setState({
value: false
});
}
if (1 != target.value) {
this.setState({
value: true
});
}
// filter out item being deleted
const updateList = list.filter(item => item.userId == target.value);
this.setState({
list3Data: updateList
});
};
render() {
const { isLoaded } = this.state;
const locations =
this.state.list2Data &&
this.state.list2Data.map(location => {
return { value: location.id, label: location.name };
});
const locationss =
this.state.list3Data &&
this.state.list3Data.map(location => {
return { value: location.userId, label: location.title };
});
//console.log(locations);
//console.log(locationss);
if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<>
<select
id="selectLocation"
value={locations.value}
onChange={this.handleChange}
>
{locations.map(({ value, label }, index) => (
<option value={value}>{label}</option>
)}
</select>
<select
id="selectLocationn"
className={this.state.value ? 'badge-primary' : 'badge-danger'}
value={locationss.value}
onChange={this.handleChange}
>
{locationss.map(({ value, label }, index) => (
<option value={value}>{label}</option>
)}
</select>
<table className="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{this.state.listData &&
this.state.listData.map(item => {
return (
<tr key={item.id.toString()}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.email}</td>
</tr>
);
})}
</tbody>
</table>
</>
);
}
}
}