NewPHPer
NewPHPer

Reputation: 237

React null value DOM Operation

import React from 'react';

class App extends React.Component {

    constructor() {
        super();

        this.state = {
            data: 'First Comes First Serves'
        }

        this.updateState = this.updateState.bind( this );
    };

    updateState( e ) {
        console.log( e );
//      console.log( e.target );
        this.setState( {data: e} );
    }

    render() {
        return (
            <div>
                <Content myDataProp = { this.state.data } updateStateProp = { this.updateState }></Content>
            </div>
        );
    }
}

class Content extends React.Component {
    render() {
        return (
            <div>
                <input type="text" value={ this.props.myDataProp } id="id" />
                <div>
                    <button onClick={ this.props.updateStateProp( document.getElementById( 'id' ).value  )}>Click</button>
                </div>
                <h3>{ this.props.myDataProp }</h3>
            </div>
        );
    }
}


export default App;

Error; Uncaught TypeError: Cannot read property 'value' of null

I'm very new at React.

Here, input value is assigned as 'First come..'(I suppose so), but error appears,

Thanks in advance.

Upvotes: 0

Views: 49

Answers (2)

blessingoraz
blessingoraz

Reputation: 33

I totally agree with Timo. I have modified the component for you:

class App extends React.Component {

  constructor() {
    super();

    this.state = {
      data: 'First Comes First Serves'
    }

    this.updateState = this.updateState.bind(this);
  };

  updateState(e) {
    this.setState({ data: e.target.value });
  }

  render() {
    return (
      <div>
        <Content myDataProp={this.state.data} updateStateProp={this.updateState}></Content>
      </div>
    );
  }
}

class Content extends React.Component {
  render() {
    return (
      <div>
        <input type="text" onChange={this.props.updateStateProp} id="id" />
        <div>
          <button onClick={this.props.updateStateProp}>Click</button>
        </div>
        <h3>{this.props.myDataProp}</h3>
      </div>
    );
  }
}


export default App;

Let me know if you are able to get it working.

Upvotes: 0

TimoStaudinger
TimoStaudinger

Reputation: 42460

When you are working with React, it is usually best to completely forget about operations that work directly on the DOM like getElementById. They will either not work at all or in unexpected ways.

Instead, have a look at the excellent React forms documentation.

The idiomatic way to do forms in React is to implement the onChange event handler of the input and store the current value in the compoenent's state. Then you can use it access and use it when the user presses the button.

Upvotes: 1

Related Questions