How to pass dynamic values to ReactJS JSS?

1.3k Views Asked by At

I need to pass dynamic values to linear-gradient in such a way shown below. How would I do this? I have tried implementing the small example of Dynamic Values on the cssinjss web site without success.

const useStyles = createUseStyles({
    card:{
        background: 'linear-gradient(to top, orange, rgb(to top, 255, props.green, 0))',
        width: '200px',
        height: '240px',
        margin: '50px',
        display: "flex",
        flexDirection: 'column',
        justifyContent: 'space-around',
        alignItems: 'center',
        color: 'white',
        fontFamily: 'arial',
        padding: 6,
        borderRadius: 15,
        composes: 'shadow'
    }
});

const WeatherCard = (props) => {
    const classes = useStyles(props);

    return (
        <div>
            <div className={classes.card}>
                <Location />
                <Icon />                
                <Tempature />
            </div>
        </div>
    );
};

WeatherCard.defaultProps = {
    green: 125
};

2

There are 2 best solutions below

4
On BEST ANSWER

Your code is correct, just missing the callback that tells the variable props with the values, try the following:

See in: https://cssinjs.org/react-jss/?v=v10.4.0#dynamic-values

const useStyles = createUseStyles({
     card: {
            background: props => `linear-gradient(to top, orange, rgb(to top, 255, ${props.green}, 0))`,
            width: '200px',
            height: '240px',
            margin: '50px',
            display: "flex",
            flexDirection: 'column',
            justifyContent: 'space-around',
            alignItems: 'center',
            color: 'white',
            fontFamily: 'arial',
            padding: 6,
            borderRadius: 15,
            composes: 'shadow'
        }
});
    
const WeatherCard = (props) => {
    const classes = useStyles({...props});

    return (
        <div>
            <div className={classes.card}>
                <Location />
                <Icon />                
                <Tempature />
            </div>
        </div>
    );
};
0
On

If it’s just one spot to put dynamic values, I would just inline style it. I understand that things need to be “perfect”, but inline styling is totally legitimate, I would use template literals as well.

So let’s say I have a component that I take a prop from.

function foo ({ green }) {
  return <div style='background:${green}'></div>
}

I used the curly brackets so I don’t need the props keyword, it understands I’m trying to grab the variable name.