Nyeon Kim
Nyeon Kim

Reputation: 137

Can't understand some codes in redux-form

I'm using some example codes from redux-form document, and I have some codes that I don't understand in renderField function.

const renderField = ({ input, label, type, meta: { touched, error } }) => {
  return (
    <div>
      <label>{label}</label>
      <div>
        <input className="form-control" {...input} type={type}/>
        {touched && error && <span>{error}</span>}
      </div>
    </div>
  )

I don't understand code below

{touched && error && <span>{error}</span>}

If touched is true... and what? I know the result, but don't know process...

Upvotes: 2

Views: 81

Answers (2)

aarosil
aarosil

Reputation: 4898

This is nothing to do with React really, it's how javascript evaluates expressions.

Here is the relevant docs

expr1 && expr2  

Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

Since the expressions are not boolean, and cannot be converted to false (such as null or undefined), it will return the last value, which in this case a span with the error in it

And, as Mayank answer mention, JSX only allows expressions. if is considered as statement, not expression, hence not allowed within JSX. So you will see react devs using other features of javascript to get back that control.

Upvotes: 3

Mayank Shukla
Mayank Shukla

Reputation: 104529

If you break the above code using if else and ternary operator, it will look like this:

1.   if(touched && error)
        <span>{error}</span>

2. if(touched)
      if(error)
         <span>{error}</span>

3. {touched && error ? <span>{error}</span> : null}

It simply means that if touched and error both are true then only render this span.

Note: if is not allowed to use inside JSX, i used it to make a clear picture. If you want to use if then call a function from render method and inside that you can use 1 and 2 way to return the span.

Upvotes: 0

Related Questions