Add CSS classes along with js code in className attribute in HTML (React)

I'm new in writting JS in React so I'm having problems in adding my css clases "block lg:hidden". I tried to do it with parenthesis. The image shows the first line of code:
No description
14 Replies
ἔρως
ἔρως8mo ago
try adding a + between ) and the string
Chris Bolson
Chris Bolson8mo ago
I don’t use React but maybe that should be something like this
<div id="slideshow" classname={`${isActive ? 'sideMenu' : null} block lg:hidden `}>
<div id="slideshow" classname={`${isActive ? 'sideMenu' : null} block lg:hidden `}>
Sorry, I am on the mobile and I can’t get the template literals to show up as the convert they mess with the code block. I wanted to show a template literal at the beginning and end of the classname
CHUIS✩
CHUIS✩OP8mo ago
Almost I needed the backticks within brackets and dollar sign for each
<div id=“slideshow” classname={`${isActive ? 'sideMenu' : null} ${'block lg:hidden'}`}>
<div id=“slideshow” classname={`${isActive ? 'sideMenu' : null} ${'block lg:hidden'}`}>
But I wanted to know why Is ok
Aoi
Aoi8mo ago
Let's divide that line into two parts
(isActive? 'sideMenu' : null)
(isActive? 'sideMenu' : null)
'block lg:hidden'
'block lg:hidden'
In the code, you are doing
"part a" "part b"
"part a" "part b"
Here if you see, you are combining two strings without any ooperator (+, -, etc) between them. So instead you need
"part a" + "part b"
"part a" + "part b"
So as @ἔρως already suggested, you just need to add a "+" between them.
ἔρως
ἔρως8mo ago
which he did, in the most overly needlessly complicated way
clevermissfox
clevermissfox8mo ago
In React, to use JavaScript within jsx you need the ${javascriptHere} so anything you want to reference that’s in JS needs to be within the brackets otherwise jsx doesn’t understand it. That’s how it was explained to me anyway.
ἔρως
ἔρως8mo ago
🤔 that's interesting makes sense, react is weird af
Aoi
Aoi8mo ago
that's not nessesory you can pass parameters inside curly braces in html
<div className={//your javascript logic}></div>
<div className={//your javascript logic}></div>
like you can do
<div className={"class-1" + "class+2"}>{true && "True!"}</div>
<div className={"class-1" + "class+2"}>{true && "True!"}</div>
Shane
Shane8mo ago
npm
classnames
A simple utility for conditionally joining classNames together. Latest version: 2.5.1, last published: 3 months ago. Start using classnames in your project by running npm i classnames. There are 42745 other projects in the npm registry using classnames.
Shane
Shane8mo ago
you may find this useful
CHUIS✩
CHUIS✩OP8mo ago
That works for props too right? {true && "True!"} This part
Aoi
Aoi8mo ago
Yeah, when returning a jsx, you can put any js code (which returns a value) inside a curly bracket. It can be a prop, inner html, etc
Aoi
Aoi8mo ago
I really should have sent this before, mb
Want results from more Discord servers?
Add your server