How To Pass Shared Props In React.

Imagine you are building a super complex React application and you have 50 shared props that you need to pass to each component. Writing all the props for every component would be very boring and redundant. Now let me show you how you can handle such a task. Below is what we I have built to explain the concept.

import React from 'react'

const Button= ({increment, color,underline})=>{
    const[counter,setCounter]=React.useState(0)

    return (

        <div onClick={()=>setCounter((previous)=>previous+increment)} style={{color,underline}}>
        INCREMENT {counter}
        </div>
    )
}

const App = () => {
const props={
  increment:1,
  underline:true,
  color:"red"
}

  return (
    <div>

      <Button {...props}/>
        <Button {...props} color="green"/>
          <Button color="green" {...props}/>

    </div>
  )
}

export default App

Basically instead of passing each prop as in

<Button color="red" increment={1} underline={true}/>,

you can create an object with these props and then spread the object for each component.

<Button {...props}/>

const obj= {
x:1
}

const object2={

x:2,
...obj,
}

object2.x for the code above will be equal to 1 because obj.x will override 2.

The same thing will also happen in <Button color="green" {...props} />

The color green will be overridden by props.color.

Its possible to share this props across multiple components by just spreading the object and this comes really handy when building complex apps that require passing a lot of props.