I\'d appreciate some help with my note taking app. Let\'s say I have 3 notes on my notes list. I want to delete the note at the top of the list. No matter which one I try to
This error is occurring from using index as your key. React uses the key attribute to track the elements inside the list. When you are deleting an element from the middle in an array, the index does not delete itself, instead it rearranges and the last index disappears. This is why the last element in your array always got deleted.
For this solution, I have provided title of the note as the key, but this may not be always unique. You will be better using a generated key or a combination of fields as key
class NoteEntry extends React.Component {
constructor(props) {
super(props);
this.state = {
display: false,
editing: false,
editTitle: this.props.title,
editDetails: this.props.details
}
this.displayToggle = this.displayToggle.bind(this);
this.edit = this.edit.bind(this);
this.save = this.save.bind(this);
}
displayToggle() {
this.setState(prevState => ({
display: !prevState.display
}))
}
edit() {
this.setState({
editing: true
})
}
save() {
let titleVal = this.refs.updateTitle.value;
let detailsVal = this.refs.updateDetails.value;
this.setState({
editTitle: titleVal,
editDetails: detailsVal,
editing: false
})
}
render() {
return (
{this.state.editing ? (
) : (
{this.state.editTitle}
)}
{this.displayTime}
{this.state.editing ? (
) : (
{this.state.editDetails}
)}
{this.state.editing ? (
) : (
)
}
)
}
}
const NoteForm = (props) => {
return (
)
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
notes: [],
title: "",
details: ""
}
this.updateTitle = this.updateTitle.bind(this);
this.updateDetails = this.updateDetails.bind(this);
this.submitHandler = this.submitHandler.bind(this);
this.deleteHandler = this.deleteHandler.bind(this);
}
updateTitle(event) {
this.setState({ title: event.target.value });
}
updateDetails(event) {
this.setState({ details: event.target.value });
}
submitHandler(e) {
e.preventDefault();
if (!this.state.title.length || !this.state.details.length) {
return;
}
const newNote = {
newTitle: this.state.title,
newDetails: this.state.details
}
this.setState(prevState => ({
notes: prevState.notes.concat(newNote),
title: "",
details: ""
}))
}
deleteHandler(id) {
this.setState(prevState => ({
notes: prevState.notes.filter((el)=> el !== id)
}))
}
render() {
return (
React Notes App
{this.state.notes.map((note,i) => (
))}
);
}
}
ReactDOM.render( , document.getElementById('root'));