-2

I want to access the value of a textfield that's being created by React. The code is below:

class Paragraph extends React.Component {
  render() {
    let style = {
      height: "150px",
      marginBottom: "10px"
    };

    return (
      <div className="paragraph" id={this.props.id}>
        <div className="row">
          <div className="col-sm-11">
            <textarea
              className="form-control"
              name={"paragraph" + this.props.id}
              placeholder="Put Paragraph Here"
              style={style}
              required
            ></textarea>
          </div>
          <div className="col-sm-1">
            <div
              className="btn btn-danger del-rotate"
              onClick={() => this.props.remove(this.props.id)}
            >
              &times;
            </div>
          </div>
        </div>
      </div>
    );
  }
}

I'm using an index.js, which contains an App and adds a Paragraph. I want to access the value typed in the textarea from my index.js, which uses Paragraph. How do I do this?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Papaya
  • 1
  • 2

2 Answers2

3

You control the values

In react when you have an input you must control the state of that input.

simple example

Using the react function useState we can control this input. state will always be our value.

const myComp = () => {
  const [state, changeState] = useState('');
  return <input type="text" onChange={e => changeState(e.target.value)} value={state} />;
};
Joe Lloyd
  • 19,471
  • 7
  • 53
  • 81
0

use props for the communication, and then pass it along. also don't forget to add change handler to your text area

For component communication :

React | pass data from parent to child component

How to pass data from parent to child in react.js

https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17

A sample for your case:

class TextArea extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      textareaValue: ''
    }
  }
  handleOnChange(event) {
    this.setState({
      textareaValue: event.target.value
    })
  }

  render() {
    return <div>
              <textarea  
                   rows={10} 
                   cols={30} 
                   value= {this.state.textareaValue} 
                   onChange={(event) => this.handleOnChange(event)}>
             </textarea>
           </div>
  }
}
joy08
  • 9,004
  • 8
  • 38
  • 73