At which point in the lifecycle should I modify my props?

I have a react component that receives some props. These props need to be mapped to a different structure in order to be usable (for a select, which expects a different structure than our store). I'm wondering at which point in the lifecycle I should do this.

I've read the documentation: https://facebook.github.io/react/docs/component-specs.html, and it recommends to keep the render function pure:

The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not read from or write to the DOM or otherwise interact with the browser

Now I'm assuming that it's still ok to map the props, as that's not state and I'm not changing them:

import React from 'react';

export default class IndicatorSelect extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const options = this.props.store.items.map(item => ({ value: item.id, label: item.name }));

    return (
      <div>Display the data in some way here: {options.value} {options.label}</div>
    );
  }
}

ThisComponent.propTypes = {
  store: React.PropTypes.object.isRequired,
};

Is this the recommended way, or should the parent component be responsible for formatting the props passed to this component? Or I should I do this in a lifecycle method, or a completely different manner?

Upvotes: 1

Views: 40

Answers (1)

Lyubomir
Lyubomir

Reputation: 20037

Yes, @selvagsz comment is right - normalising props inside render is not that bad unless you do it heavily. If it's "too much", I would create a container component that normalises the props and passes them to a presentational one that only takes care of rendering.

It is not easy to answer the question, but a rule of thumb I follow is:

A presentational component should receive its props in the most convenient / normalised way possible so that it only takes care of rendering.

However, for normalisation as in your example it doesn't make sense to create additional container component - the overhead is too big at this point. When you start feeling the pain of converting props, create a container component and let it convert them for you or do it in the parent if it's already a container.

Upvotes: 2

Related Questions