Shorn Jacob
Shorn Jacob

Reputation: 1251

React - Passing State to child component

My Parent Class which holds the overall App state

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: 1,
    };

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

  handleChange(event) {
    const target = event.target;
    const newValue = target.value;

   if( Math.sign(newValue) === 1 ) {
    this.setState({
      inputValue: newValue
    });
   }

  }

  render() {
    return (
      <EngInput type="number" value={this.state.inputValue} onChange={this.handleChange}/>
    );
  }
}

My child component to which I am passing the state as props.

class EngInput extends React.Component {

  render() {
    return (
      <input
        type="number"
        defaultValue={this.props.value}
        onChange={this.props.onChange}
      />
    );
  }
}

The logic I am trying to implement being - The child input component should accept only positive numbers. If its a negative number, the state should not change and the UI should update to the inputValue instead of the newValue.

But, whats happening in the above code is, even though the state does not change to non negative value, the UI still accepts negative value.

How to implement a logic like, if the value is negative, the UI should still show the old positive value from state.

Upvotes: 1

Views: 2345

Answers (1)

Tholle
Tholle

Reputation: 112897

Use value instead of defaultValue to control the input from the parent component.

class EngInput extends React.Component {
  render() {
    return (
      <input
        type="number"
        value={this.props.value}
        onChange={this.props.onChange}
      />
    );
  }
}

Upvotes: 3

Related Questions