How can I do conditional rendering on a styled component?

What does “styled component” mean?

Styled-components is one of the most widely used CSS in JS techniques; it is not a new technique, so it is reliable to use, and this technique is still being refined, so I chose it. But in essence, there are numerous alternatives in this area (such as emotion), so you can select whichever you prefer because these libraries have a variety of characteristics and advantages.

Conditional styling: What Is It?

It modifies CSS according to a set of circumstances or a state. Among the many distinct methods that CSS may be added in React, inline styles or styled components can be used to update or add CSS based on a condition.

Consider a toggle menu. Conditional styling will be utilized to reveal or conceal the menu based on a state in this scenario. Similarly, we may use this technique to open and close a popup.

function styleComp() {
  const [open,setOpen] = useState(false)
  const styles = {
    popup:{
      display:"inline",
      float:'right'
    }
  };
  return (
    <div>
      <button onClick={()=>{setOpen(true)}}>Click</button>
      <div className="popup" style={styles.popup}>
        <h1>Bosc Tech labs</h1>
      </div>
    </div>
  );
}

Also Read: Top 10 Techniques For React Performance Optimization in 2022

Styled component inside if-else logic:

Boilerplate code and redundancy are decreased by using if-else logic inside stylized components.

Previously, you had to modify the className attribute based on a property value to use styled components:

const style1 = styled.div`
  padding: 5px 10px;   
  background: papayawhip;  
`;
const style2 = styled.div`  
  padding: 5px 10px;   
  background: papayawhip;  
`;


<>   
  {BooleanValue   
    ? <div className="style1`">Value</div>
    : <div className="style-2">Value</div> 
  }
</>

Styled component inside Ternary operator logic:

const style1 = styled.div`
  height: ${props => props.size === 'small' ? '30px' : '60px'}
  width: ${props => props.size === 'small' ? '30px' : '60px'} 

Styled component inside Logical operator logic:

const Style = styled.div`
  height: ${({size}) =>
  size === 'small' && '25px' ||
  size === 'large' && '100px' ||  
  '50px'
  };
  width: ${({size}) => size === 'small' && '25px' ||  
  size === 'large' && '100px' ||
  '50px'
  }';
 
<Box/>
<Box size="small"/>
<Box size="large"/>

Schedule an interview with React developers

Example:

import { React, useState } from "react";
import styled from "styled-components";
import "./App.css"
function StyleComponent() {
  const [open,setOpen] = useState(false)
  const Style = styled.div`
    display: ${open ? "flex" : "none"};
    opactiy: ${open ? "1" : "0"};
  `;
  return (
    <div>
      <button onClick={()=>{setOpen(true)}}>Click Here</button>
      <Popup className="Style">
        <h1>This is a popup!</h1>
      </Popup>
    </div>
  );
}
export default StyleComponent;

Example:

import React from "react";
import styled from "styled-components";

const style = styled.div`
 width:300px;
 height:150px;
 color:black;
 background-color: ${props =>
  props.category === 'Study' ? 'blue'
  : props.category === 'Work' ? 'Gray'
  : props.category === 'Shooping' ? 'Black'
  : 'green'};

 const Demo = () => {
  return (
  <>
    <style
      category='Study'>Study
    </style>
    <style
      category='Work'>Work
    </style>
    <style
      category='Shopping'>Shopping
    </style>
  </>
)
}
export default Demo

Conclusion:

The styled-components package has allowed us to create a new method of styling our components. Additionally, we’ve found that when compared to the conventional method of styling using className and assigning said property CSS classes, our component’s DOM declaration looks more meaningful.

Even if you want to use a UI framework, styled-components is a very strong toolkit. It can considerably speed up the writing and styling of your own controls.

I hope you got the idea of how to do the conditional rendering on the styled component with React. Moreover, we are the leading react app development company with a team of React experts ready to help you. Let us know your requirements if you want to develop your application with React framework. Get in touch with us!

Frequently Asked Questions (FAQs)

1. What is the toggle in ReactJS development?

In simple terms, toggling means viewing and hiding the elements alternatively with each click of a button. A similar concept is needed in many huge apps like showing and hiding notifications.

2. Why is the react component rendered twice?

It happens because of the intentional feature of React. StrictMode. It will happen only in the development phase and help you find the accidental side effects in the render phase.

3. Which operator is used to render the react component conditionally?

The use of a ternary operator conditionally renders the react component.

4. How do you pass the ref to styled components?

We can pass refs into the styled component for accessing the DOM properties and the methods for a provided styled component. For example, when we give the ref created with the useRef hook into the input, the useEffect will call inputRef.


Book your appointment now

Get in touch






    Stay up-to-date with our blogs