Search code examples
reactjsreact-nativeemotion

Emotion.js how to do composition / conditional styling in react-native?


https://github.com/emotion-js/emotion/tree/master/packages/native

gives example

    style={css`
      border-radius: 10px;
    `}

However, I can't figure out how I can do composition as done in https://emotion.sh/docs/composition with react-native

    <div css={[danger, base]}>

Nor I can't do conditional styling as done in https://emotion.sh/docs/styled

const Button = styled.button`
  color: ${props =>
    props.primary ? 'hotpink' : 'turquoise'};
`

Even if I could do, they use two different methods one using css one using styled . How can I get the two at the same time with react-native?


Solution

  • Question 1: How to do composition in emotion/native in React Native?

    It's really simple all you need to is use style property like so:

    const style1 = css`
      font-size: 40px;
    `
    
    const color = css`
      color: red;
    `
    
    // And then in your component you can pass the all your style objects 
    // in an array to style property
    <Text style={[fontSize, color]}>Hello world</Text>
    

    Question 2: Conditional style in emotion/native in React Native?

    const Description = styled.Text`
        font-size: ${props =>  props.fontSize !== undefined ? props.fontSize : "40px"};
      color: hotpink;
    `
    
    <Description fontSize={"60px"}>
    Change code in the editor and watch it change on your phone! Save to get a shareable url.
    </Description>
    

    Here's a working exampe as a snack