Search code examples
javascriptreactjsreact-nativereact-props

Spread props from multiple components


I'm creating a component that have 2 other components inside. I would like to spread props for both of them so I'm able to use props for each one of them. How can I direct the style prop? i.e

import FirstComponent from '../components'
import SecondComponent from '../components'

function SimpleButton (props) {
  return (
    <FirstComponent
      {...props}
    >
      <SecondComponent
        {...props}
      />
    </FirstComponent>
  )
}

function HomeScreen () {
  return (
    <SimpleButton
      style={this is the style for FirstComponent}
      style={this is the style for SecondComponent}
    />
  )
}

Solution

  • You can rename keys:

    function SimpleButton (props) {
      return (
        <FirstComponent
          {...props, style: props.firstComponentStyle}
        >
          <SecondComponent
            {...props, style: props.firstComponentStyle}
          />
        </FirstComponent>
      )
    }
    
    function HomeScreen () {
      return (
        <SimpleButton
          firstComponentStyle={this is the style for FirstComponent}
          secondComponentStyle={this is the style for SecondComponent}
        />
      )
    }