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);
Related videos on Youtube
Comments
-
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?
-
AndrewL64 over 5 yearsPossible duplicate of Styled Components: props for hover
-
-
msqar about 2 yearsIMO nested ternaries like that should be avoided if possible, it's pretty bad when it comes to readability.
-
joedotnot almost 2 yearswhere do you set shouldHoverRed, shouldHoverGreen, shouldHoverOrange ??!