So my issue is that I have a drop-down menu and the items are a bit strange. The first row looks blank and the data that I have looks like this.
I know the first user has a username: null and that is probably why the blank is showing but in the frontend I want to change the username of user of index 0 to always say "Myself" whether it is null or not. How Do I do modify its value?
This is how the drop-down looks like
async componentDidMount() {
const ep = `${process.env.REACT_APP_API}/partners/roles`;
const users = await axios.get(ep);
if (users.data.success) {
this.setState({
users: users.data.data.users.filter(f => !f.isArchived)
});
}
console.log("Users", users)
if (this.props.item) {
this.setState({
id: this.props.item.id,
description: this.props.item.description,
due: this.props.item.due,
priority: this.props.item.priority,
assigned: this.props.item.assigned
});
}
}
This is where the drop-down items are being generated
<select
name="assigned"
id="assignedto"
type="text"
className="form-control"
style={{ width: "70%" }}
onChange={e => {
this.setState({
assigned: e.target.value
});
}}
>
<option value="">Myself</option>
{this.state.users.map(e => (
<option value={e.id} key={e.id}>
{e.username}
</option>
))}
</select>
Maybe use the index?
<select
name="assigned"
id="assignedto"
type="text"
className="form-control"
style={{ width: "70%" }}
onChange={e => {
this.setState({
assigned: e.target.value
});
}}
>
<option value="">Myself</option>
{this.state.users.map(e => (
<option value={e.id} key={e.id} index>
index == 0 ? 'Myself' : {e.username}
</option>
))}
</select>
You can add a check while rendering like this:
<option value={e.id} key={e.id}> {e.username ? e.username : 'Myself'} </option>
Usually the right approach is to clean your data when you're setting the state:
users.forEach((u => { if (!u.name) { u.name = 'Myself'; } }));