pingeyeg
pingeyeg

Reputation: 680

How to work with classes that change in styled-components

This question may have been asked, but I'm having trouble finding the answer. I'm new to styled-components, but slowly starting to appreciate them. I'm trying to understand how to grab the class name considering they change dynamically. The code I'm doing is:

styled-component

export const NavOpen = styled.div`
  position: absolute;
  top: 25px;
  left: 30px;
  transition-property: all;
  transition-duration: 0.2s;
  transition-timing-function: linear;
  transition-delay: 0s;
  width: 35px;
  height: 25px;
  overflow: hidden;
  cursor: pointer;
  z-index: 1;
`;

javascript

const slideInWindow = display => {
  if (display) {
    const navWindow = document.querySelector(".sc-ifAKCX");
    navWindow.classList.add("slidein");
  }
};

JSX

<NavOpen onClick={() => slideInWindow(true)}>
  <Bar1 />
  <Bar2 />
  <Bar3 />
  {display && <X onClick={() => closeWindow(false)} />}
</NavOpen>

The class .sc-ifAKCX was something different before. I'm sure I'm going at this wrong, but trying to understand how I should query the class if it's going to change on me.

Upvotes: 1

Views: 1035

Answers (1)

Robbie Milejczak
Robbie Milejczak

Reputation: 5770

You can give each styled component a class name of your choosing:

export const NavOpen = styled.div.attrs({
  className: 'slidein-target'
})`
  position: absolute;
  top: 25px;
  left: 30px;
  transition-property: all;
  transition-duration: 0.2s;
  transition-timing-function: linear;
  transition-delay: 0s;
  width: 35px;
  height: 25px;
  overflow: hidden;
  cursor: pointer;
  z-index: 1;
`;

Now every NavOpen instance will have the class slidein-target in it's classlist, which you can use as your query selector.

Note that slidein-target will not replace the generated class name sc-XXXXXX but will appear alongside it.

Upvotes: 4

Related Questions