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;