Search code examples
javascripthtmlcssreactjsstyled-components

how to conditional render a styled component in react?


I have a styled-component that I want to render only when the screen size is above 480. I tried doing that by getting a reference to the element and disabling it. but that didn't work. I set the display property to nonebut then the button is still there it's clickable.

Here is my code

 console.log(window.screen.width);
  if(window.screen.width <= 480) {
    var a = document.getElementsByClassName("Button1")
    ...
    ...
    ...
    ...
  }

  return (
    <>
      <div className="control">
        <Circle onClick={handleVideoToggle}>
          <img src={video ? Video : VideoOff} />
          </Circle>
        <Circle onClick={handleAudioToggle}>
          <img src={audio ? Mic : MicOff} />
        </Circle>
        <Circle onClick={handleScreenToggle}>
          <img className = "Button1" src={screen ? Screen : ScreenOff} />
        </Circle>
        <Circle onClick={handleCallDisconnect}>
          <img src={End} />
        </Circle>
      </div>
    </>
  );
};

export default Controls;

const 
  Circle = styled.div`
    width: 45px;
    height: 45px;
    border-radius: 50%;
    display: flex;
    cursor: pointer;
    :not(:first-child) {
      margin-left: 20px;
    }
  `,
  Image = styled.img`
    max-width: 100%;
    width: 45px;
    margin: 0 auto;
  `;


Solution

  • You can remove that "if" block at the top. You can conditionally include Circle/Button in what you return, like this:

      const isSmall = window.screen.width <= 480;
      return (
        <>
          <div className="control">
            <Circle onClick={handleVideoToggle}>
              <img src={video ? Video : VideoOff} />
              </Circle>
            <Circle onClick={handleAudioToggle}>
              <img src={audio ? Mic : MicOff} />
            </Circle>
            {!isSmall && (<Circle onClick={handleScreenToggle}>
                  <img className = "Button1" src={screen ? Screen : ScreenOff} />
                </Circle>)
            }
            <Circle onClick={handleCallDisconnect}>
              <img src={End} />
            </Circle>
          </div>
        </>
      );