Categories
React Tips

React Tips — Function Props, Query Strings, and Default Props

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.

Listen to State Changes in React

We can listen to state changes to React in several ways.

In class components, we can use the componentDidUpdate hook to listen for state and prop changes.

We can write:

componentDidUpdate(object prevProps, object prevState)

There’s also the componentWillUpdate method which is deprecated.

With function components, we can use the useEffect hook to watch for changes.

For instance, we can write:

const [name, setName] = useState('foo');
useEffect(getSearchResults, [name])

We pass in an array with the variables that we want to watch in the 2nd argument of the useEffect hook.

The first argument is a callback that’s called when name changes.

Pass Props in Link with React Router

We can pass in a query string to the Link .

For instance, we can write:

<Link to={{ pathname: `/foo/bar`, query: { backUrl } }} />

We set the query property with an object.

The object’s keys and values are transformed into a query string that’s attached after the pathname .

We can also take URL parameters with placeholders:

<Route name="/foo/:value" handler={CreateIdeaView} />

Then we can get it by using:

this.props.match.params.value

To get the query string, we can write:

this.props.location.search

to get the value.

Then we can use the URLSearchParams constructor to parse it and the values in it:

new URLSearchParams(this.props.location.search).get("foo")

If we have a query string ?foo=bar , then that will return 'bar' .

Call Parent Method with React

We can call a parent component’s method if we pass a function from the parent to the child as a prop.

For instance, we can write:

import React, {Component} from 'react';

class Child extends Component {
  render () {
    return (
      <div>
        <button
          onClick={() => this.props.someFunc('foo')}
        >
          click me
        </button>
      </div>
    )
  }
}

class Parent extends Component {
  someFunc(value) {
    console.log(value)
  }

  render() {
    return (
      <div>
        <Child
          someFunc={this.someFunc.bind(this)}
        />
      </div>
    )
  }

}

We pass the function from parent to child with the someFunc prop in the Parent component.

Then in the Child component, we call the function with this.props.someFunc .

Using function components, we can write:

import React from "react";

function Child(props){
  return(
    <>
      <button onClick={props.parentFunc}>
        click me
      </button>
    </>
  );
}

function Parent(){
  const parentFunc = () => {
    console.log("parent func called");
  }

  return (
    <>
      <Child
        parentFunc={parentFunc}
      />
    </>
  );
}

We have the Parent component which has the parentFunc that we pass to the Child component as a prop.

Then we called it by calling props.parentFunc when we click on the button in the Child component.

Import and Export Components Using React, ES6 and Webpack

To export components in a React project, we should export it as a default export.

For instance, we can write:

SomeNavBar.js

import React from 'react';
import Navbar from 'react-bootstrap/lib/Navbar';

export default class SomeNavBar extends React.Component {
  render(){
    return (
      <Navbar className="navbar-dark" fluid>
        {//...}
      </Navbar>
    );
  }
}

Then we import it with whatever name we want.

For instance, we can write:

import SomeNavBar from './SomeNavBar';

to import the navbar component.

We don’t put curly braces in default exports.

Set component Default Props on React Component

To set default props on a React component, we can use the prop-types package.

We’ve to install it by running:

npm i prop-types

Then we can write:

import PropTypes from 'prop-types';

class Address extends React.Component {
  render() {
    const { street, city } = this.props;
    <p>{street}, {city}</p>
  }
}

Address.defaultProps = {
  street: 'street',
  city: 'city',
};

Address.propTypes = {
  street: PropTypes.string.isRequired,
  city: PropTypes.string.isRequired
}

We set the defaultProps property to set the default prop values.

The object has the prop names as the keys and the default values as the values.

propTypes has the prop types for each prop.

We set them both to string and make them required with isRequired .

Conclusion

We can set default props and validate their format with the prop-types package.

We listen to state changes with class component lifecycle methods or the useEffect hook for function components.

Also, we can get and set query strings and URL parameters with React Router.

We can pass functions as props from parent to child.

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 *