slindsey3000
slindsey3000

Reputation: 4291

How to set this input value when 0 is falsey ReactJS

ReactJS does not like null for a value in <input>.

Warning: value prop on input should not be null. Consider using an empty string to clear the component or undefined for uncontrolled components.

Great. My database often returns null because nothing has been set yet.

I am dynamically rendering input fields in a ReactJS app.

value={this.state[row_array[0]] || ''} 

The value for this.state[row_array[0]] will sometimes be 0. I want to put 0 in the text field but this evaluates to false ... thus... the empty string '' is put in the text field.

The problem is this.state[row_array[0]] could be anything... 0 is the big problem.

This has some info but nothing helpful for me https://github.com/facebook/react/issues/11417

Any ideas about how I can set that value=0?

Upvotes: 1

Views: 3078

Answers (2)

Ra&#250;l C. Rivero
Ra&#250;l C. Rivero

Reputation: 297

When asked for a variable, either with an if or with a ternary operator, it is evaluated to be non-null and non-undefined.

You can try.

class X extends React.Component {
    state = {};
    render (){
      const xdata = this.state[row_array[0]];
      const value = xdata ? xdata : '';
      return (
        <input type="text" value={value} />
      )
    }
}

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 371118

Use the conditional operator instead, and check for null:

value={this.state[row_array[0]] === null ? '' : this.state[row_array[0]]} 

Setting the value of an input this way tells React that you want to control the component. If it's uncontrolled initially, this will result in a warning - to avoid that warning, make sure to specify that the input is controlled from the start.

Live demo:

const row_array = [0];
class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = { 0: null };
    this.updateData = this.updateData.bind(this);
  }

  updateData (event) {
    console.log('updated');
    this.setState({ [event.target.name]: event.target.value });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input id={row_array[0]} className="data-input" name={row_array[0]} placeholder="" value={this.state[row_array[0]] === null ? '' : this.state[row_array[0]]} onChange={this.updateData} />
      </form>
    );
  }
}

ReactDOM.render(
  <NameForm />,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

If it may also be undefined, and not just null, then check that as well:

value={this.state[row_array[0]] === null || this.state[row_array[0]] === undefined ? '' : this.state[row_array[0]]} 

Upvotes: 6

Related Questions