How to send props to a variable on the basis of system wide theme in javascript?

Viewed 148

How to send props to a component on the basis of system wide theme?

I know how to style my components with media query for dark and light themes with @media prefers-color-scheme , but I am working with react-json-vew library and component, it takes a theme prop, which I need to change when the system wide dark mode is toggled.

Its a custom component so I would not like to style it on my own, that would also increase the code's length.

Snippet :

import ReactJson from "react-json-view";
import React from "react";

class JsonDialog extends React.Component {
constructor(props) {
    super(props);

    this.state = {
      checked: false,
      copied: false
    };
  }
render(){
        return    <ReactJson src={json} theme={"apathy:inverted"} /> // here I need to apply theme on the basis of dark or light mode

  } 
}
3 Answers

Why don't you use React Context API?

import React from 'react';

const ThemeContext = React.createContext();

export default class App extends React.Component { 
  render() {
    return (
      <ThemeContext.Provider value={'apathy:inverted'}>            
            <JsonDialog/>       
            {/* Other Components */}
      </ThemeContext.Provider>
    )
  }
}

class JsonDialog extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            checked: false,
            copied: false
        };
    }
    render() {        
        return( 
            <ThemeContext.Consumer>
                {theme=> <ReactJson src={json} theme={theme} />}
            </ThemeContext.Consumer>
        )
    }
}

So the easiest way is to receive a prop to your component that will describe if its in dark mode or light mode. I'll do the following example:

import ReactJson from "react-json-view";
import React from "react";

class JsonDialog extends React.Component {
constructor(props) {
    super(props);

    this.state = {
      checked: false,
      copied: false
    };
  }
render(){
    const themeName = this.props.dark ? 'apathy':'apahty:inverted'
    return    <ReactJson src={json} theme={themeName} /> // here I need to apply theme on the basis of dark or light mode
  } 
}

Another way is to use redux or some kind of state management for your app, but if its a simple app, the above should work.

This should do the trick

<ReactJson src={json} theme={this.props.dark ? "darkThemeName" : "lightThemeName"} />
Related