How do you do conditional hovering in styled components?

11,259

Solution 1

This will work:

export const Container = styled.div`
    ${ props => props.shouldHover 
        ? '&:hover { background: red }' 
        : ''
    }
`;

Solution 2

You can try something like the following, that may help:

import { css, styled } from 'styled-components'

styled.div`
   ${props => props.shouldHover && css`
      &:hover {
        background: 'red';
      }
   `}
`

Solution 3

This works for me

import React from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
const Container = styled.div`
  & > h2 {
    &:hover {
      background: ${props => (props.shouldHover ? "red" : "none")};
    }
  }
`;
function App({ shouldHover }) {
  return (
    <Container shouldHover>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic shappen!</h2>
    </Container>
  );
}

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

Codesandbox

Share:
11,259

Related videos on Youtube

Red Baron
Author by

Red Baron

JavaScript, ReactJS.

Updated on June 04, 2022

Comments

  • Red Baron
    Red Baron almost 2 years

    I have a component that based on certain props I want the ability to change the background on hover. but based on other props, hover should do nothing. is this possible?

    export const Container = styled.div`
    
        &:hover {
            background: ${({ shouldHover }) => shouldHover ? 'red' : '' };
        }
    `
    

    however this does not work. any suggestions how this can be done?

  • msqar
    msqar about 2 years
    IMO nested ternaries like that should be avoided if possible, it's pretty bad when it comes to readability.
  • joedotnot
    joedotnot almost 2 years
    where do you set shouldHoverRed, shouldHoverGreen, shouldHoverOrange ??!