Reputation: 93
I have a textarea and i want to push its content into an array that I defined
I have created a Tasks component and used the onClick property to push the value of its textarea's innerhtml into the array.
App.js :
import React from 'react';
import Tasks from './tasks.js';
import './App.css';
let tasks= [
{name:""},
{name:""},
{name:""},
{name:""},
{name:""}
]
function App(props) {
return (
<div className="App">
<Tasks onClick={()=>{
tasks.push(this.props.value)
}} />
</div>
);
}
export default App;
tasks.js:
import React from 'react'
class Tasks extends React.Component {
render() {
return (<div>
<textarea value={this.props.value} ></textarea>
<button onClick={this.props.onClick}>Add task</button>
</div>)
}
}
export default Tasks
The app compiled successfully, but when I click on the button, the "Cannot read property 'props' of undefined" error appears
Upvotes: 0
Views: 1727
Reputation: 20755
Maintain state in child component to store value of text-area,
constructor(props) {
super(props)
this.state = {
value: '',
}
}
You can set state value, when your text-area change,
handleChange = e => {
this.setState({value: e.target.value})
}
On the click of the button, you need to pass the value from text-area to parent component like,
<textarea value={this.state.value} onChange={this.handleChange} />
<button onClick={() => this.props.onClick(this.state.value)}>
Add task
</button>
In parent component, you can push value of text-area into your array.
function addData(val) {
tasks.push(val)
console.log(tasks)
}
<Tasks onClick={value => addData(value)} />
Upvotes: 1