Post/Code

HomeAboutUsesNow

React Tips.

These are some tips when coding with React:

Components

  • When creating components, use the component first before implementing it. That is to say, use the planned component in the parent before you have coded it so you can think about the interface before implementing the code.

  • When creating components, give props generic names so that you do not tightly bind the name of props to the type of the data in the current implementation. Chances are good that when you look to re-use the component with another data source or context, the name of your prop may no longer suit. In cases, whe you are not certain what the props data names might be, you can pass props that specify the name of the field to be read, then in the component, you can use item[value] square bracket notation for object properties as opposed to item.value dot notation for properties. This makes your components more generic.

Default Props

You can set default props if you think most components or data that will be used will use the same property names. For example: _id or name. You can use default props as follows:

ComponentName.defaultProps = {
    valueProperty: “_id”,
    textProperty: “name”,
};

This will enable you to pass the necessary props only when they will differ from the default props.

Event Bubbling

Note that when you do something like this when bubbling an onClick event:

<ComponentList
    items={this.state.items}
    currentItem={this.state.currentItem}
    onClick={item => this.handleItemSelection(item)}
/>

The function looks like this:

handleItemSelection(item) {
    ... do something ...
}

You can achieve the same thing like this:

<ItemsList
    items={this.state.items}
    currentItem={this.state.currentItem}
    onClick={this.handleItemSelection}
/>

With a function like this:

handleItemSelection = item => {
    ... do something ...
}

Object Destructuring

When you are often referencing this.props in your component, it helps to use object destructuring to simplify.

In a class component, within the render() method, but before the return statement, you can do the following:

const { onClick, currentGenre, genres } = this.props;

Then, where you would have used, for example: this.props.onClick or this.props.currentItem, you can instead use onClick or currentItem.

When using a function component, you will enter the same object destructuring code within the component function, and before the return statement. For example:

const ItemList = props => {
    const { items, textProperty, valueProperty, onItemSelect } = props;
    ...
}