0
render(){
  const { loading } = this.state;
  return(
    <div>
      {!loading ? <input disabled type='text' /> : <input type='text' />}
    </div>
  )
}

Above jsx make sense? I didn't get any compliation error, just that I got a warning from react saying Unknown propdisabbedon <input> tag.

How to changed the attr of the button to disabled the correct way? Imagine if my input has lots of class of css, do I need to repeat them too? I felt it's redundant.

Fez Vrasta
  • 14,110
  • 21
  • 98
  • 160
Giala Jefferson
  • 1,809
  • 8
  • 20
  • 29

1 Answers1

2

You don't need a conditional rendering on the input tag. You can do it the following way

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true
    }
  }
  render(){
    const { loading } = this.state;
    return(
      <div>
        <input disabled={loading} type='text'/>
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('app'));
<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="app"></div>
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • Note that using `constructor` to set the initial `state` is discouraged, also, when you use `super`, you should pass the `...props` to it as well in case you are going to use `this.props` in the same context. Better to use the class properties syntax. (`state = { ...stuff }`) – Fez Vrasta Apr 09 '17 at 11:52
  • @FezVrasta I agree with you that props should be passed to the constructor and super otherwise it can lead to potential bugs. However why is it discouraged to set state constructor. see https://facebook.github.io/react/docs/react-component.html#constructorhttp://stackoverflow.com/questions/37782403/set-initial-react-component-state-in-constructor-or-componentwillmount and – Shubham Khatri Apr 09 '17 at 11:58
  • The doc makes use of the `constructor` because it's more widespread, but it leads to more bugs because of what I explained. You can refer to `this.props` inside a class property and avoid any `super` quirkiness. https://gist.github.com/FezVrasta/630e92170d20618fc35d55c83fefcd2d – Fez Vrasta Apr 09 '17 at 12:00