I have a ponent 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?
I have a ponent 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?
Share Improve this question asked Jan 18, 2019 at 9:44 Red BaronRed Baron 7,65212 gold badges46 silver badges109 bronze badges 1- Possible duplicate of Styled Components: props for hover – AndrewL64 Commented Jan 18, 2019 at 10:08
4 Answers
Reset to default 11This will work:
export const Container = styled.div`
${ props => props.shouldHover
? '&:hover { background: red }'
: ''
}
`;
You can try something like the following, that may help:
import { css, styled } from 'styled-ponents'
styled.div`
${props => props.shouldHover && css`
&:hover {
background: 'red';
}
`}
`
This works for me
import React from "react";
import ReactDOM from "react-dom";
import styled from "styled-ponents";
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
You can make the background conditional based on what props you pass down. Below is an example where the div changes based on multiple different conditions.
const Container = styled.div`
background: blue;
&:hover {
background: ${props => props.shouldHoverRed
? 'red'
: props.shouldHoverGreen
? 'green'
: props.shouldHoverOrange
? 'orange'
: 'blue'
};
}
`
default is blue and depending on the prop passed it will render different colors for the background on hover.