I’m new to react. I’m trying to add a conditional render inside a map. I’m not sure if my syntax is incorrect or if it’s just a simple bracket.
This is a simple todo list with an edit button. If the editing
state is true, it shows the input field otherwise it shows the task. To shorten the code, I’ve only kept the editing portion but there would be a delete button as well.
import React, { Component } from "react";
class ClassInput extends Component {
constructor(props) {
super(props);
this.state = {
todos: ["Just some demo tasks", "As an example"],
inputVal: "",
editing: false,
};
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleInputChange(e) {
this.setState((state) => ({
...state,
inputVal: e.target.value,
}));
}
handleEdit() {
return (
<input
type="text"
name="task-entry"
value={this.state.inputVal}
onChange={this.handleInputChange}
/>
);
}
render() {
return (
<section>
<h3>{this.props.name}</h3>
<form onSubmit={this.handleSubmit}>
<label htmlFor="task-entry">Enter a task: </label>
<input
type="text"
name="task-entry"
value={this.state.inputVal}
onChange={this.handleInputChange}
/>
<button type="submit">Submit</button>
</form>
<h4>All the tasks!</h4>
<ul>
// ternary operator
{this.state.todos.map((todo) => (
<li key={todo}>
{this.state.editing ? (
<input
type="text"
value={todo}
/>
) : (
{todo}
<button onClick={() => this.handleEdit()} type="edit"> // issue is here expected ","
Edit
</button>
)}
<button onClick={() => this.handleDelete(todo)} type="delete">
Delete
</button>
</li>
))}
</ul>
</section>
);
}
}