简体   繁体   中英

React curly braces inside quotes to ads className

I'm trying to add a class name if a button is clicked

className={"collapse"+{active? "expand":null}}

If a button is clicked i want to add a class name expand along with collapse . But I'm getting syntax error.

This should work:

className={ collpase ${active? "expand": undefined} collpase ${active? "expand": undefined} }

While this won't work:

className={"collapse" + {active ? "expand" : null}}

This will:

className={"collapse" + active ?  "expand" : null}

The curly braces you used are syntax for creating an object, which isn't what you're trying to do here.

use backticks

 className={ `${active?"eexpand":null }`}

As answers above suggest, this will work:

className={"collapse" + active ?  "expand" : null}

But I would actually suggest using Template literals because it's more clean and performant.

This would look as such:

className={`collapse ${active ?  "expand" : ""}`}

You can use template strings such as:

className={`collapse ${active ?  "expand" : ""}`}

But I recommend clsx library:

className={ clsx( 'collapse', active && 'expand' ) };

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