Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS in JS, how to make props.className the priority class

We need components where the class passed as props should have more priority than the default class.

When passing classes as a prop, the component gives priority to the class created in his own file.

Text.jsx

// this will be a component in another folder, it will be used in the whole app so it 
// should haveDYNAMIC styling
function Text(props) {
  const useStyles = makeStyles(theme => ({
    default: {
      fontSize: 18,
      color: "black"
    }
  }));

  const classes = useStyles();

  return (
    <div className={classNames(classes.default, props.className)}>
      {props.children}
    </div>
  );
}

App.jsx

function App() {
  const useStyles = makeStyles(theme => ({
    title: {
      fontSize: 80,
      color: "red"
    },
    notGoodPractice: {
      fontSize: "80px !important"
    }
  }));
  const classes = useStyles();

  return (
    <div className="App">
      <Text className={classes.title}>Text in here is 18px</Text>
      <Text className={classes.notGoodPractice}>
        Text in here is 80px
      </Text>
    </div>
  );
}

React Snippet => CodeSandBox

like image 836
Renaldo Balaj Avatar asked Nov 06 '22 11:11

Renaldo Balaj


1 Answers

You can prioritise classes passed as props this way.

Just make sure you don't apply makeStyles on it so that you can access them correctly in child.

import React from "react";
import ReactDOM from "react-dom";
import { makeStyles } from "@material-ui/core/styles";

// this is how we will use the Text component
function App() {
  const style = {
    title: {
      fontSize: "80px",
      color: "red",
      "@media (max-width: 767px)": {
         color: "green"
      }
    },
    notGoodPractice: {
      fontSize: "80px"
    }
  };

  return (
    <div className="App">
      <Text class1={style.title}>Title should be with size 80px</Text>
      <Text class1={style.notGoodPractice}>Title should be with size 80px</Text>
    </div>
  );
}

// this will be a component in another folder, it will be used throw the in app so it should be as DYNAMIC as possible
function Text(props) {
  const useStyles = makeStyles(theme => ({
    default1: {
      fontSize: 18,
      color: "black"
    },
    priorityClass: props => props.class1
  }));

  const { default1, priorityClass } = useStyles(props);
  return <div className={`${default1} ${priorityClass}`}>{props.children}</div>;
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Check out live sandbox https://codesandbox.io/s/zen-voice-mb60t

like image 56
kooskoos Avatar answered Nov 12 '22 11:11

kooskoos