Capsuling many props in React

Problem

Tomoharu Tsutsumi
2 min readFeb 9, 2021

--

Sometimes, we face code which has many props in React. The example is like this.

export default ComponentA extends React.Component {  render(){ 
return (
<ComponentB a={a} b={b} c={c} d={d} e={e} f={f} g={g} h={h} i={i} j={j} // ...more props />
)
}
}

export default ComponentB extends React.Component {
render(){ const {a, b, c, d, e, f, g, h, i, j //...more props} = this.props <ComponentC a={a} b={b} c={c} d={d} e={e} f={f} g={g} h={h} i={i} j={j} // ...more props />
} //In ComponentC, these props are not used.
}export default ComponentC extends React.Component { render(){ const {a, b, c, d, e, f, g, h, i, j //...more props} = this.props // more codes...
}
}

This design has a problem that Component B knows the detail of props, though Component B doesn’t use those props. Those props are used in Component C. That is to say, Component B knows information that it doesn’t need to know…

Solution

In my case, I made it an object.

export default ComponentA extends React.Component {  render(){ 
return (
<ComponentB settings={{a: a, b: b, c: c, d: d, e: e, f: f, g: g, h: h, i: i, j: j}}/>
)
}
}
export default ComponentB extends React.Component { render(){ const { settings } = this.props <ComponentC settings={settings}/>
}
}export default ComponentC extends React.Component { render(){ const { settings } = this.props <div>{settings.a}</div> // used liked this
}
}

Component B came not to know the details by capsuling.

Started LinkedIn as well!

https://www.linkedin.com/in/tomoharu-tsutsumi-56051a126/

--

--

Tomoharu Tsutsumi

Software Engineer with 4 + years of professional experience.