conditional rendering in styled components

后端 未结 5 2213
失恋的感觉
失恋的感觉 2020-12-07 14:19

How can I use conditional rendering in styled-components to set my button class to active using styled-components in React?

In css I would do it similarly to this:<

5条回答
  •  我在风中等你
    2020-12-07 15:00

    I didn't notice any && in your example, but for conditional rendering in styled-components you do the following:

    // Props are component props that are passed using  etc
    const StyledYourComponent = styled(YourComponent)`
      background: ${props => props.active ? 'darkred' : 'limegreen'}
    `
    

    In the case above, background will be darkred when StyledYourComponent is rendered with active prop and limegreen if there is no active prop provided or it is falsy Styled-components generates classnames for you automatically :)

    If you want to add multiple style properties you have to use css tag, which is imported from styled-components:

    I didn't notice any && in your example, but for conditional rendering in styled-components you do the following:

    import styled, { css } from 'styled-components'
    // Props are component props that are passed using  etc
    const StyledYourComponent = styled(YourComponent)`
      ${props => props.active && css`
         background: darkred; 
         border: 1px solid limegreen;`
      }
    `
    

    OR you may also use object to pass styled, but keep in mind that CSS properties should be camelCased:

    import styled from 'styled-components'
    // Props are component props that are passed using  etc
    const StyledYourComponent = styled(YourComponent)`
      ${props => props.active && ({
         background: 'darkred',
         border: '1px solid limegreen',
         borderRadius: '25px'
      })
    `
    

提交回复
热议问题