Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to target styled components class names?

Im using styled components to build an app and need to reuse some components on another page but some of the style properties are slightly different.

Is it safe to do something like

div.Card-sc-17xtaz4-0 {
  box-shadow: unset;
  margin-top: unset;
  margin-bottom: unset;
}

or is the class name associated to the styled component likely to change at build time?

like image 330
L-R Avatar asked Sep 18 '19 13:09

L-R


1 Answers

It's not random, but it uses a hash library for the name and that will change if any prop of your component happen to change. Actually, it will change even if you add an extra space character inside your component CSS.

See the snippet below and try to uncomment the color:red; line and you'll see that the className changes. Comment it back EXACTLY as it was before and you'll get the old className back.

const Container_DIV = window.styled.div`
  /* color: red; */
`;

function App() {
  const container_ref = React.useRef(null);
  const [classList,setClassList] = React.useState(null);
  
  React.useEffect(() => {
    setClassList(container_ref.current.classList);
  },[]);
  
  return(
    <Container_DIV
      ref={container_ref}
    >
      I am Container_DIV, a styled-component!
      <div>
        <b>My className is: </b>{classList}
      </div>
    </Container_DIV>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<script src="//unpkg.com/styled-components/dist/styled-components.min.js"></script>
<div id="root"/>

From: https://medium.com/styled-components/how-styled-components-works-618a69970421

Currently styled-components uses MurmurHash algorithm to create uniq identifier and then converts the hash number to alphabetic name.

Generating CSS class name:

Each component instance with uniq props has it’s own CSS class name which generated by means of the same MurmurHash algorithm but from the componentId and the evaluatedStyles string:

enter image description here

like image 118
cbdeveloper Avatar answered Sep 30 '22 12:09

cbdeveloper