RyanHaraki
RyanHaraki

Reputation: 71

How to dynamically update styled-components in React?

So on a project I'm working on I want to be able to update the theme of my website when a user changes the currentTheme variable which is set up using useState, and references some objects I have in another file with predefined styles. I am having trouble updating and setting these styles up using styled-components.

I currently have it so whenever the user changes the theme(which is done in another component) it will update the current chosen theme. As you can see there's a console.log there, and the background colour does update accordingly, it just doesn't work with the styled-components. I would like to state that I have tried moving the styled.div into my CodeContainer component and it worked there, but the performance of the app was HORRIBLE when I made that change.

I basically need to know how to update a variable in the styled.div. Should I pass through props instead? Should I move it in another way? Not too sure what to do here. Thanks in advance for any help!

import React, { useState } from "react";
import Editor from "./Editor";
import { monokai, solarizedDark, terminal, textmate } from "./ui/themes";
import styled from "styled-components";

const CodeContainer = ({ setHtml, setCss, setJs, setRenderDoc, theme }) => {
  let currentTheme = monokai;

  if (theme === "textmate") {
    currentTheme = textmate;
  } else if (theme === "solarized_dark") {
    currentTheme = solarizedDark;
  } else if (theme === "terminal") {
    currentTheme = terminal;
  }

  return (
    <Container background={currentTheme}>
      <Editor
        setHtml={setHtml}
        setRenderDoc={setRenderDoc}
        languageName="html"
        theme={theme}
      />
      <Editor
        setCss={setCss}
        setRenderDoc={setRenderDoc}
        languageName="css"
        theme={theme}
      />
      <Editor
        setJs={setJs}
        setRenderDoc={setRenderDoc}
        languageName="javascript"
        theme={theme}
      />
    </Container>
  );
};

export default CodeContainer;

const Container = styled.div`
  background: ${(currentTheme) => currentTheme.background};
  height: 40vh;
  border-bottom: 4px #211e1c solid;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 15px;
`;

Upvotes: 0

Views: 1871

Answers (1)

Kasi
Kasi

Reputation: 747

Use the following syntax. Docs.

const Container = styled.div((props) => ({
  background: props.background,
  height: "40vh",
  borderBottom: "4px #211e1c solid",
  //..
}));

Note: Make sure to use the camelCase syntax with CSS properties.

Upvotes: 1

Related Questions