Vladimir Zyuzin Vladimir Zyuzin - 1 year ago 38
React JSX Question

How can i get <textarea> value in parent component from child?

The aim of my application is to get some array of messages(mes) from api-url and send answer(subFunction method)for every message. After that message will be delete from 'mes' array. 'Message' is a parent component responsible for fetch data(componentDidMount event) and rendering message through map method. 'MessageItem' responsible for get value from 'textarea' - the body of answer. But i can't transfer this.state.value(textarea.value) from from MessageItem to parent component. If i place 'subFunction' in child component, i can't change this.state.mes

import React from 'react'
import ReactDOM from 'react-dom'
const url="api-url";

class MessageItem extends React.Component {
constructor(props) {
super(props);
this.state = {
value:'',
};
};

handleChange(event) {
this.setState({value: event.target.value});
}
render() {
return (
<div className="message_wrap" key={this.props.message_id}>
<div className="message_body">
{this.props.message_body}
</div>
<div className="input-field col s12">
<textarea value={this.state.value} onChange={this.handleChange.bind(this)}/>
<label htmlFor="textarea1">
Ответ
</label>
<button onClick={this.props.onClick}>
Отправить
</button>
</div>
</div>
);
}
}
class Message extends React.Component {
constructor(props) {
super(props);
this.state = {
mes:[],
};
};
componentDidMount(){
fetch(url).then(function(response){
return response
}).then(function (response) {
return response.json()
}).then((data)=>{
this.setState({mes:data})
})
}
subFunction(user_id, value) {
/*This method have to send answer with user id and textarea value*/
}
render() {
return (
<div>
{this.state.mes.map((index)=>
(
<MesItem
key={index.message_id}
message_body={index.message_body}
onClick={this.subFunction.bind(this, index.user_id)}
/>

)
)
}
</div>
);
}
}
ReactDOM.render(<Message/>, document.getElementById('container'));

Answer Source

You are passing a function from parent component to child, call that function to pass the value from child to parent.

Like this:

<button onClick={() => this.props.onClick(this.state.value)}>
     Отправить
</button>

Now do console.log inside subFunction it will print proper value:

subFunction(user_id, value) {
   console.log(user_id, value)
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download