Vladimir
Vladimir

Reputation: 428

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"> ?

Upvotes: 11

Views: 33920

Answers (3)

Hasibul Alam Rahi
Hasibul Alam Rahi

Reputation: 312

incase if you want to insert inline styling using style tag in next.js , you have to insert an object inside the style={} tag as all of the style and classNames in next are considered as object . For example you want to insert the background colour of your div using the insline styling than do the followings <div style={{ ["background-color" as any]: "#ffc107" }}></div> do make sure that You use semicolons to insert style properties

Upvotes: 2

Cloud Gem
Cloud Gem

Reputation: 181

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',

Upvotes: 13

Vladimir
Vladimir

Reputation: 428

@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

Upvotes: 15

Related Questions