How to conditionally add a className?

蹲街弑〆低调 提交于 2019-12-11 05:22:09

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/44856989/how-to-conditionally-add-a-classname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!