Return JSON from sass through window.getComputedStyle in React

Viewed 66

My team is attempting to migrate our app over to styled-components, but we still have a lot of variables defined in our sass files. I have managed to send our sass variables through a sass function, and then return them in our React as a string using window.getComputedStyle().

The problem is that I cannot JSON.parse() the string even though it is formatted as json. Is there anyway to pass JSON from sass to React/Javascript?

Sass:

@function export-vars(){
    @return "{'$theme-color': ' #3A82C3 !default'}";
}

body::before {
  content: export-vars();
}

React:

    useEffect(() => {
        const tmp = window.getComputedStyle(document.body, '::before')
        console.log(typeof tmp)
        console.log(tmp)
    })
1 Answers

This is how I achieved it with an array of colors which is exported as a string and parsed in JavaScript.

colors.scss
$system-colors: ( primary: #cc0000, battleship-grey: #888888 );
@function color-map($map) {
    $result: ();
    @each $key, $value in $map {
        $result: append($result, '"#{$value}"', comma);
    }
    @return $result;
}
:export {
    systemColors: #{color-map($system-colors)};
}

and in your component

component.js
import { systemColors } from './colors.scss'
const myColors = JSON.parse('[' + systemColors + ']')
Related