1

Using reactjs only, is it possible to do advanced styling similar to

#primary-nav .list-group-item.active {}
// or
#secondary-nav .list-group-item:hover>.background-item {}

in the first example I could do some rather simple javascript logic to figure out if the component is "active" but on the second example it's just so much simpler with css.

Is there a clear react+js solution for these situations that comes close to the simplicity of css?

Jacksonkr
  • 31,583
  • 39
  • 180
  • 284

1 Answers1

2

className is applied exactly like a regular HTML class. So to correctly target .background-image like in

.list-group-item:hover>.background-item

Your jsx structure should look like

import './index.css'

const Component = () =>{
    return(
        <div className='list-group-item'>
            <div className='background-item' />
            <span>
                <div className='background-item' /> /*Targeting nested items '>' */
            </span>
         </div>
     )
}

You can use jss and clsx to have dynamic and conditional styles. Here is an example using MUI styles(hooks API), but you can use styled components, react-jss or implement you're own style's solution based on jss.

   import { makeStyles } from '@material-ui/styles'
   import clsx from 'clsx'

   const styles = {
       root:{
           color: 'white',
           '&:active':{
                color: 'red'
            }
       },

       hidden:{
           opacity: 0
       }
   }

   const useStyles = makeStyles(styles)

   const Component = ({ open }) =>{
       const classes = useStyles()

       const rootStyle = clsx({
           [classes.root] : true,
           [classes.hidden] : !open
       })

       return <div classsName={rootStyle} />
   }

jss also have lots of cool features like theming support, styles interpolation (a personal favorite), nested selectors, style's rules,etc. Definitely worth taking a look.

Notice that clsx doesn't require jss to work, it's just a helper to conditionally apply classes. You can use it like clsx({'foo' : true, 'bar': false})

Dupocas
  • 20,285
  • 6
  • 38
  • 56