AnnaSm
AnnaSm

Reputation: 2300

React, is there a way to avoid needing to wrap a div inside a div?

I have the following:

const errorMessage = ({meta}) =>
  <div>
    {meta.error && meta.touched && <div className="alert alert-info" role="alert">{meta.error}</div>}
  </div>

If I remove the outer div wrapper in the above I get an error... Is there a way to get errorMessage to work without the extra DIV?

Thanks

Upvotes: 0

Views: 270

Answers (2)

sigidhanafi
sigidhanafi

Reputation: 11

You can write like this :

const errorMessage = ({meta}) => {
return (meta.error && meta.touched) ? `<div className='alert alert-info' role='alert'>${meta.error}</div>` : null
}

Upvotes: 0

Mayank Shukla
Mayank Shukla

Reputation: 104479

You can write it like this by using {}:

const ErrorMessage = ({meta}) => {

    if(meta.error && meta.touched)
        return <div className="alert alert-info" role="alert">{meta.error}</div>

    return null;
}

Or remove the outer div and remove the {} also, use ternary operator to put the condition, like this:

const ErrorMessage = ({meta}) => meta.error && meta.touched ? 
    <div className="alert alert-info" role="alert">{meta.error}</div>
    : null;

You need to use ErrorMessage instead of errorMessage, check the reason here:

Html is not rendering in the browser - React js

Check this answer why it was failing when you removed the outer div:

const errorMessage = ({meta}) => 
    {meta.error && meta.touched && <div className="alert alert-info" role="alert">{meta.error}</div>}

Upvotes: 1

Related Questions