Search code examples
twitter-bootstrapreactjsreact-reduxredux-form

How to conditionally add a className?


I have the following with react-redux-form:

<fieldset>
  <label>{label}</label>
  <div>
    <input {...input} name="email" type="text" className="form-control" />
    {touched && error && <span className="error">{error}</span>}
  </div>
</fieldset>

I would like to be able to update <fieldset> with either

className=""
className="has-success"
className="has-danger"

The logic would be:

  • If touched but no error: <fieldset className="has-success">
  • If touched and error: <fieldset className="has-danger">
  • If not touched nor error: <fieldset className="">

How can I get this working in React?


Solution

  • You could implement it like so:

    <fieldset className={touched ? (error ? "has-danger" : "has-success") : ""}> 
      ... 
    </fieldset>
    

    This first checks if touched is truthy. If it is, only then will it render a <fieldset> which class will be "has-danger" if error is truthy or "has-success" otherwise. If touched, doesn't exist, then the class is an empty string. This assumes that there will be no case where touched is falsey and error is truthy (though you could add more to handle that case).

    If you find that this is a bit unreadable, maybe try using the classnames NPM package which is a bit more readable:

    <fieldset className={classNames({
      "": !touched && !error,
      "has-danger": touched && error,
      "has-success": touched && !error
    })}>
      ...
    </fieldset>
    

    This is more readable and doesn't assume there won't be a case where touched is falsey and error is truthy.