Home > Back-end >  React.js won't include className using states inside a ternary operator
React.js won't include className using states inside a ternary operator

Time:04-12

I'm trying to make a react website in pure css (no bootstrap) with an open/close sidebar. To do this I need to set and change css classes for elements on the page and have their visual updates apply instantly. Working on a very simple example where there is a state const [setShowGreenBox, showGreenBox] = React.useState('true'); And I'm trying to have this applied/removed to elements to display css data

.showGreenBox{
    background:green
}

.bigPinkText{
    color: pink;
    font-size: 50px;
}
import React from 'react'
import './SidebarColorsTemplate.css';

const SidebarColorsTemplate = ({ children }) => {
    const [setShowGreenBox, showGreenBox] = React.useState('true');
    
    //this.setShowGreenBox('true')

    return (
        <>
        <div>SidebarColorsTemplate Page Top Content</div>
        
        <div className='bigPinkText'>String classNames</div>
        <div className={"bigPinkText " "showGreenBox "}>String classNames inside brackets</div>
        showGreenBox={showGreenBox}
        <div className={"bigPinkText "   (showGreenBox==='true' ? "showGreenBox" : "")}>ternary  operator logic</div>
        <hr></hr>
        {children}
        <hr></hr>
        <div>SidebarColorsTemplate Page Bottom Content</div>
        

        </>
    )
}

export default SidebarColorsTemplate

CodePudding user response:

Make it simple with Template literals and Boolean

import React from 'react'
import './SidebarColorsTemplate.css';

const SidebarColorsTemplate = ({ children }) => {
const [showGreenBox,setShowGreenBox] = React.useState(true);


return (
    <>
    <div>SidebarColorsTemplate Page Top Content</div>
    
    <div className='bigPinkText'>String classNames</div>
    <div className={"bigPinkText " "showGreenBox "}>String classNames inside brackets</div>
    showGreenBox={showGreenBox}
    <div className={`bigPinkText ${showGreenBox?'showGreenBox':''}`}>ternary  operator logic</div>
    <hr></hr>
    {children}
    <hr></hr>
    <div>SidebarColorsTemplate Page Bottom Content</div>
    

    </>
  )
}

export default SidebarColorsTemplate

CodePudding user response:

Using a string in the state looks like a weird choice in this case, it makes more sense to do:

const [showGreenBox, setShowGreenBox] = useState(true);

<div className={`bigPinkText ${showGreenBox && 'showGreenBox'}`}>ternary  operator logic</div>

Another option would be to just do:

const [showGreenBox, setShowGreenBox] = useState('showGreenBox'); // you can set this to an empty string instead of using false, but it's riskier (you could accidentally set it to an unexisting style)

<div className={`bigPinkText ${showGreenBox}`}>ternary  operator logic</div>
  • Related