Home > database >  React Binding syntax
React Binding syntax

Time:06-10

Disclaimer: I am a .NET developer that is now trying to learn reactjs.

I am making a simple doodle / drawing app for my own tutorial. As a simple first step, I wanted to provide a way for them select the pen color by entering something like Red, Green, or #880000 (hex code).

This is how I implemented it, is there a simpler / neater way?

NOTE: the state variable is defined in the constructor and includes penColor and a few other properties.

<div className='penControls'>
    <div>Pen Color 
        <div className='colorPicker' >
            <input type="text" id="penColor" name='penColor' defaultValue={this.state.penColor}
                onChange={
                     (ev) => {
                         this.state.penColor = document.getElementById('penColor').value;
                         this.setState(this.state);
                     }
                }
                className="penColorPicker mx-4" />
        </div>
    </div>
</div>

CodePudding user response:

If you're working with React you should avoid the use document API, so there's no need of document.getElementById, use event.target.value that is sent in the event object when calling onChange

Also, never assign a value to your state directly like this

this.state.foo = 'bar';

Use setStatefunction for this:

this.setState({ foo: 'bar' })

That'll dispatch all the component life cycle related to re-rendering in a safe way

Finally, try with the following code...

<div className='penControls'>
    <div>Pen Color 
        <div className='colorPicker' >
            <input type="text" id="penColor" name='penColor' defaultValue={this.state.penColor}
                onChange={
                     (ev) => {
                         const newPenColor = event.target.value;
                         this.setState({ penColor: newPenColor });
                     }
                }
                className="penColorPicker mx-4" />
        </div>
    </div>
</div>

CodePudding user response:

ReactJS tries to solve the exact problem you are facing of reading from DOM and updating the state. But we need to update the state in React way.

    <div className='penControls'>
<div>Pen Color 
    <div className='colorPicker' >
        <input type="text" id="penColor" name='penColor' defaultValue={this.state.penColor}
            onChange={
                 (ev) => {

                     let newPenColor = this.state.penColor
                     this.setState({ penColor: newPenColor });
                 }
            }
            className="penColorPicker mx-4" />
    </div>
</div>

React State Update

  • Related