1

I have below CSS and mark up in reactJS and want to update background property dynamically. Let's say for few cases, it should be red and for few black.

   goodOne: {
    position: 'relative',
    '&:before': {
        position: 'absolute',    
        background: 'This value needs to be filled dynamically',
        borderRadius: '50%'        
    }
}

<div className = {classes.goodOne}>Hello world</div>

How can i do that?

1

1 Answer 1

2

ReactJSS documentation

import React from 'react'
import {createUseStyles} from 'react-jss'

const useStyles = createUseStyles({
  myButton: {
    padding: props => props.spacing
  },
  myLabel: props => ({
    display: 'block',
    color: props.labelColor,
    fontWeight: props.fontWeight,
    fontStyle: props.fontStyle
  })
})

const Button = ({children, ...props}) => {
  const classes = useStyles(props)
  return (
    <button className={classes.myButton}>
      <span className={classes.myLabel}>{children}</span>
    </button>
  )
}

Button.defaultProps = {
  spacing: 10,
  fontWeight: 'bold',
  labelColor: 'red'
}

const App = () => <Button fontStyle="italic">Submit</Button>

Example (Codesandbox)

import React from 'react';
import { ThemeProvider, createUseStyles } from 'react-jss';

const useStyles = createUseStyles((theme) => ({
  background: {
    color: theme.color,
    background: ({ background }) => background,
    width: 300,
    height: 300
  }
}));

function MyComponent() {
  const [background, setBackground] = React.useState('black');

  const classes = useStyles({
    background: background
  });

  return (
    <React.Fragment>
      <div className={classes.background}>Hello, world</div>

      <button onClick={() => setBackground('red')}>Change to red</button>
      <button onClick={() => setBackground('black')}>Change to black</button>
    </React.Fragment>
  );
}

function App() {
  const theme = {
    color: 'green'
  };

  return (
    <ThemeProvider theme={theme}>
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
      </div>

      <MyComponent />
    </ThemeProvider>
  );
}

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for sharing this, Could you please share me a working example. I tried to run this code snippet for getting error.
@Lara, codesandbox.io/s/interesting-sea-ig24d (also I've updated the answer)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.