简体   繁体   中英

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

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>}

You can write like this :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM