I'm sorry if this is a frequent question but it's something I'm reallly struggling to understand.
I'm building a basic to-do list app in React.
The container currently contains a form that takes in the information, and adds each item inputted an items array in the state. I then have a 'TaskList' component that takes this state and renders my tasks.
What I want to do is create a separate form component, instead of having the form within my container.
The issue is that if I just copy the code for the form into a new component, the state it will modify is its own, and therefore won't be accessible via the TaskList component to render the list of tasks.
Is there any way to have a component that can update the state of its parent component. My source code is below for reference.
export default class Container extends React.Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
items: []
}
}
handleSubmit(e) {
e.preventDefault();
var itemsArray = this.state.items;
itemsArray.push(e.target.elements.task.value);
this.setState({
items: itemsArray
})
e.target.reset();
}
render() {
return (
<div className="">
<header className="header">TODO</header>
<form onSubmit={this.handleSubmit}>
<input name="task" placeholder="Task"></input>
<button type="submit">Add</button>
</form>
<TaskList data={this.state.items} />
</div>
);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
const TaskList = props => {
var tasks = (props.data).map( (item, key) => { return <Task data={item} key={key} /> })
return(
<ul className="gif-list">
{tasks}
</ul>
);
}
export default TaskList;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>