Categories
React Tips

React Tips — Props, this Binding, and Side Effects

Spread the love

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at some tips for writing better React apps.

Conditionally Pass Prop Inline to a Component

We can conditionally pass prop inline to a component by passing in an expression as the prop value.

For instance, we can write:

<Child {...(this.props.canEdit ? { editOptions : this.state.options } : undefined)} >

We check the canEdit prop to see if it’s truthy.

If it is, then we pass in the editOptions prop to the child.

Otherwise, we passed in undefined .

We use the spread operator to spread the returned objects into props.

Use One or Many useEffect Hooks in a React Component

We can use the useEffect hook as many times as we want.

For instance, we can write:

useEffect(() => {
  // run code
  return () => {
    // run clean up code
  }
}, []);

useEffect(() => {
  // run code when props.foo changes
  return () => {
     // run clean up code when props.foo changes
  }
}, [props.foo])

The first useEffect call is used for running code when the component loads.

The function we return is run when the component unmounts.

In the 2nd useEffect call, we run code when props.foo changes.

And the function that’s return runs clean up code when props.foo changes.

It’s useful for triggering any side effects like an API call or anything like that.

Pass Properties Object to Child Component

We can pass an object’s properties to a child component by using the object spread operator.

For instance, we can write:

return <Child {...props} />;

The all the properties in the props object will be passed into Child as props.

Avoid Binding ‘this’ to Every Method

We can avoid binding all our methods to this by using class fields.

This isn’t part of the JavaScript syntax, but it can be used with Babel or TypeScript.

For instance, we can wire:

class Foo extends React.Component {

  onClick = () => {
    console.log('clicked');
  };

  onMouseOver = () => {
    console.log('mouse over');
  };

  render() {
    return (
      <div
        onClick={this.onClick}
        onMouseOver={this.onMouseOver}
      />
    );
  }

}

It’s still in Stage 3, so it’s not final.

Push Method in React Hooks

We can’t use the push method to append an item to an array since it returns the item that’s appended and changes the array in place.

Instead, we’ve to return a new array with the item that we wan tot append.

For instance, we can write:

const [array, setArray] = useState(initialArray);

Then we write:

setArray(oldArray => [...oldArray, newItem]);

We get the old array and return a new array with the items appended.

The existing items are spread into the new array with the spread operator.

PropTypes Check Object with Dynamic Keys

We can use a function to check an object with dynamic keys when we validate props.

For instance, we can write:

someProp: (props, propName, componentName) => {
  if (!/match/.test(props[propName])) {
    return new Error('match prop doesn't exist');
  }
}

We check if the value of someProp if the value of someProp matches the regex pattern we specified.

If it doesn’t then we throw an error.

props has the props as an object.

propName has the name of the prop.

componentName has the component name.

React propTypes: objectOf vs shape

The objectOf method methods lets us check if a prop value is of a certain type.

For instance, we can write:

number: PropTypes.objectOf(PropTypes.number)

to check if the value of the number prop is an object.

On the other hand, shape lets us check for the structure of an object.

For instance, we can write:

styleObj: PropTypes.shape({
  color: PropTypes.string,
  fontSize: PropTypes.number
}),

Then the styleObj prop has to have the color property, which is a string.

And it should have a fontSize property which is a number.

Conclusion

There are various ways to check the shape of an object we pass in as props.

We can pass properties into an object optionally by specifying a ternary expression.

Also, we can use useEffect multiple times in our component.

Dynamic keys can also be checked with custom functions with the prop-types package.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *