conditional prop react code example

Example 1: conditional jsx property

render() {
  return (
    <a className="navbar-brand" {... url ? {href: url} : {}}>Logo</a>
  )
}

Example 2: conditional style prop react

style={{ textDecoration: todo.completed && "line-through" }}

style={{ textDecoration: todo.completed ? "line-through" : 'none' }}

Example 3: conditional props react

// single prop
propName={ condition ? something : somethingElse }
propName={ condition && something }
// multiple props
{ ...( condition ? { ...setOfProps } : { ...setOfOtherProps })}
{ ...( condition && { ...setOfProps })}

Example 4: How do I conditionally add attributes to React components?

var InputComponent = React.createClass({
    render: function() {
        var required = true;
        var disabled = false;

        return (
            <input type="text" disabled={disabled} required={required} />
        );
    }
});

Example 5: react if statement

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.    </div>
  );
}