Cleaning up render functions

I love using the spread operator to clean up my prop passing when working with React, which I always placed in my render.

I love using the spread operator to clean up prop passing when working with React, which I always placed in render.

render() {
  const componentProps = {dog: 'dog', cat: 'cat'}
  return (
    <div>
      <MyComponent {...componentProps}/>
    </div>
  )
}
One level of abstraction for prop passing. But we can go deeper. One more level of abstraction. >

Why

I found myself writing a component with 7 children, all of which needed props (will probably need refactoring later on). I was declaring my props, as normal, in my render. But it ended up being 30 lines of code before I even returned anything.

I have a solution

Make an entirely new function and create all your props there.

  get childComponentProps() {
  const componentProps = {dog: 'dog', cat: 'cat'}
  return { componentProps };
}

render() {
  const { componentProps } = this.childComponentProps;
  return (
    <div>
      <MyComponent {...componentProps}/>
    </div>
  )
}

My render with 7 components went from 50 collective lines down to 2 lines of prop creation lines before the return statement. Finally back to a readable state.

Comments

Popular posts from this blog

Contrasting var and ES6s new declarations: let and const

Modularity vs. Abstraction. Which is More Important?

Unit testable components pt.3: Testing components