Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react props undefined inside the constructor and exist inside the render

I'm trying to create a controlled text area.

class TextArea extends React.Component {
  constructor(props) {
    super(props);
    this.state= {
        text: this.props.initial
    };
    this.handleChange = this.handleChange.bind(this);
  }

handleChange(event) {
    //some handle
}

render() {
    return (
        <textarea
          value={this.state.text}
          placeholder={this.props.initial}
          onChange={this.handleChange}
        />
    );
  }
}

For some reason if I console.log the this.props.initial in the constructor I get an undefined.

But the placeholder works.

What I would like to do is to ditch the placeholder and set an initial value to that the user can edit and copy and interact with. (basically normal text and not a placeholder, but I cannot do that because it doesn't work)

What am I doing wrong?

Edit: The way that I am passing props.initial to the textarea:

<TextArea
  initial={this.state.json.initial}
  text={this.state.json.text}
  changeHandler={this.handleChange}
/>

I am getting the json from a $.getJSON call and I think that the textarea gets rendered before the json call is finished. Is there any way to run the render function only after the componentWillMount function?

like image 369
Wolfyaskingstuff Avatar asked Oct 30 '22 00:10

Wolfyaskingstuff


1 Answers

Remove this from this.props in the constructor since you have access to props from its argument list.

class TextArea extends React.Component {
  constructor(props){
    super(props)
    
    this.state = {
      text: props.initial,
    }
    
    this.handleChange = this.handleChange.bind(this)
  }
  
  handleChange(event){
    this.setState({ text: event.target.value })
  }
  
  render(){
    return (
      <div>
        <div>Initial text: {this.props.initial}</div>
        <textarea
          value={this.state.text}
          placeholder={this.props.initial}
          onChange={this.handleChange}
        />
      </div>
    )
  }
}

ReactDOM.render(
  <TextArea />,
  document.getElementById('root')
)
<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>


<div id="root"></div>
like image 106
mersocarlin Avatar answered Nov 15 '22 04:11

mersocarlin