Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Inline style with css variable in next.js

Doing components for app. For section want to add ability to pass some optional accent color to get output like:

<section style="--mycolor:red">
... //contents
</section>

where "red" can be passed in backend during page build as color name, #hex, "rgba()" or "hsla()" strings. It gives opportunity to use that color to children elements of this section - for border colors, first letters, markers, backgrounds etc.

Simple code^:

<section style={`--mycolor:{color}`};>

does not work because next expects mappable code, but looks like css variables names aren't parse-able in inline syntax. I can also inject it with <style jsx> statement:

<style jsx>{`
    section{
        --mycolor:  ${ color != '' ? color : 'var(--default-color)'};
    }
`}
</style>

but this soluition looks "dirty" for such simple task - adds tons of unnecessary code just to serve one css rule.

I think it can be achieved with something like

<section styles={myStyle}>

where myStyle is jsx style object, but i don't understand how to manually create it (in examples its only imported prop w/o details where did it get from).

So is there a way to achieve simple output like <section style="--mycolor:red"> ?

like image 511
Vladimir Avatar asked Mar 04 '26 03:03

Vladimir


2 Answers

@juliomalves, thanks for help, final solution is like

style={{ '--mycolor': color }}> where:

'--mycolor' = css variable name quoted as string (css properties are not quoted !)

color = prop of an element

like image 82
Vladimir Avatar answered Mar 07 '26 02:03

Vladimir


If using TypeScript with Nextjs, there is very simple solution as blow

{{ ['your css variable name' as any] : your value}}

e.g.

['--rating' as any]: 2.5,
['--star-color' as any]: '#b3b3b3',
like image 22
Cloud Gem Avatar answered Mar 07 '26 03:03

Cloud Gem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!