简体   繁体   中英

Passing prop to styled component

I'm trying to find a way to dynamically create a 'center this div' component. This code currently works but is a bit verbose and not very dry:

const Rel = styled.div`
    position: relative;
    height: 100%;
    width: 100%;
    `

const Abs = styled.div`
    position: absolute;
    top: 50%;
    `

const LeftAbs = styled(Abs)`
    left: 0;
    transform: translateY(-50%);
`
const RightAbs = styled(Abs)`
    right: 0;
    transform: translateY(-50%);
`
const CenterAbs = styled(Abs)`
    left: 50%;
    transform: translate(-50%, -50%);
`


const Centered = ({ children, ...props }) => {

    let abs = <CenterAbs>{children}</CenterAbs>

    if (props.center) {
        abs = <CenterAbs>{children}</CenterAbs>
    } else if (props.left) {
        abs = <LeftAbs>{children}</LeftAbs>
    } else {
        abs = <RightAbs>{children}</RightAbs>
    }

    return (
        <Rel>
          {abs}
        </Rel>
    )


}

I'd like to do it in a different way by passing a prop down to the Abs component, something like this (below) where the top level element Centered receives a prop, then dynamically passes that into the component beneath.

const Abs = styled.div`
    position: absolute;
    top: 50%;
    ${props => props.left ? "left: 0;" : "right: 0;"}
    `



const Centered = ({ children, ...props }) => {

    const { direction } = props

    return (
        <Rel>
          <Abs direction>{children}</Abs>
        </Rel>
    )

}

// ...passed into:
const Header = () => {
  return (
    <HeaderContainer>
      <Centered direction="left">
        <h1>Raph37</h1>
      </Centered>
    </HeaderContainer>
  )
}

Is this possible (or best practice)? I've tried many different ways of doing it and would love a bit of a guidance.

What you've written should almost work and your approach is one of the right way of performing this, according to this section of the documentation.

With <Abs direction> , you're passing direction = true . This is not what you want. Modify it with <Abs direction={direction}> .

Note that sometimes you won't wish to modify the UI component, and you can override it with the css prop from styled-component wherever you are. You can, for example, do this :

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

const Abs = styled.div`
    position: absolute;
    top: 50%;
`

const Centered = ({ children, direction }) =>
    <Rel>
      <Abs css={direction === 'left' ? css`left: 0;` : css`right: 0;`}>
        {children}
      </Abs>
    </Rel>
}

You can find more informations about css prop in styled-component here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM