12

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

1
  • 2
    Have you tried <section style={{ '--mycolor': 'red' }}>? Commented Aug 26, 2021 at 15:26

3 Answers 3

16

@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

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

Comments

14

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

1 Comment

so should we use {{a as any: b}} or [a as any]: b?
2

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

Comments

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.