Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React.js won't include className using states inside a ternary operator

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading