This maybe a silly question, so I apologize in advance.
I have a small array where I iterate it with this.state.data.map() and pass the data into inputs. I would like to edit the data in each input and save the new data. Since it's an array, how can I save this new data into the array? Which is the best/smartest practice for this?
Here is an example below:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: ["Saab", "Volvo", "BMW"],
editMode: false
};
}
handleInput = e => {
let value = e.target.value;
let name = e.target.name;
console.log(name);
console.log(value);
this.setState(prevState => ({
data: {
...prevState.data,
[name]: value
}
}));
};
handleFormSubmit = e => {
e.preventDefault();
const { data } = this.state;
console.log(data);
};
render() {
return (
<div className="App">
<div>
{!this.state.editMode ? (
<button onClick={() => this.setState({ editMode: true })}>
edit
</button>
) : (
<div>
<button onClick={() => this.setState({ editMode: false })}>
cancel
</button>
<button onClick={this.handleFormSubmit}>submit</button>
</div>
)}
</div>
<React.Fragment>
{this.state.data.map((rule, index) =>
this.state.editMode ? (
<form onSubmit={this.handleFormSubmit}>
<input
onChange={this.handleInput}
type="text"
placeholder="Cars"
name={rule}
defaultValue={rule}
key={index}
/>
</form>
) : (
<p key={rule}> - {rule} </p>
)
)}
</React.Fragment>
</div>
);
}
}
Thank you! :)
state.data? Else every identical value will be replaced with new one.