最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do you do conditional hovering in styled components? - Stack Overflow

programmeradmin7浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 11

This 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.

发布评论

评论列表(0)

  1. 暂无评论