As the title suggests, I'm attempting to target an array inside of my state object but as you would guess if you ever tried. This isn't as straightforward as it sounds. I've looked through a couple of questions here (React: How do I update state.item[1] on setState? (with JSFiddle) and ReactJS - setState of Object key in Array) but neither are solving my problem.
What I need is to target a specific index inside of the noteData array, and update it according to whatever a user types into the <TextArea /> component. Not exactly sure why but my noteData array just read as an array with an empty string noteData = [''].
If you need a more in-depth look, you can go to https://stackblitz.com/edit/note-taking and fork the page and edit it yourself. The file structure is goofy to the say the least. I started using redux and decided against it halfway through.
state and functions TextArea
class NoteList extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: '',
noteName: [],
noteData: [],
selectedNote: []
}
}
handleInputValue(e) {
this.setState({
inputValue: e.target.value
});
}
addNoteFunc(e) {
this.setState({
noteName: [ ...this.state.noteName, e.target.value ],
noteData: [ ...this.state.noteData, '' ]
});
}
// everytime the user types, change the value of noteData
handleNoteData(e, index = this.state.selectedNote[0]) {
const copyNoteData = Object.assign({}, this.state);
copyNoteData.noteData[index] = e.target.value;
this.setState(copyNoteData);
}
handleSelectedNote(index) {
this.setState({
selectedNote: [ index ]
});
}
<textarea
value={this.state.noteData[this.state.selectedNote[0]]}
handleNoteData={(e, index) => this.handleNoteData(e, index)}
/>
The actual TextArea component
import React from 'react';
const TextArea = props => {
return (
<div className='textarea'>
<textarea
value={props.value}
onKeyDown={props.handleNoteData}
/>
</div>
);
}
export default TextArea;
indexwill always be undefined in this setup. Here you are expecting index:handleNoteData={(e, index) => this.handleNoteData(e, index)}, but in you're not passing that in hereonKeyDown={props.handleNoteData}. Soindexwill always end up being the same thing. That may be the reason.handleSelectedNotefunction is overwriting the state each time with a new array. Sothis.state.selectedNotewill never have a length more than 1.state.selectedNoteis supposed to be a length of 1, always. It is as the name suggests, the currently selected note which can only be one. In myhandleNoteDatafunc, im not sure if I'm doing it right but theindexargument is defined asthis.state.selectedNote[0]...handleNoteData(e, index = this.state.selectedNote[0])so I should not need to pass a value later on, as it has already been defined, or am I using this incorrectly?indexas a number?