Categories
React Tips

React Tips — Pass Props, Background Image, and Window Resize

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.

Pass Props to Handler Component with React Router

We can pass props to the route handler component with render props.

For instance, we can write:

<Route path="/greeting/:name" render={(props) => <Greeting greeting="Hello, " {...props} />} />

Then we can define our Greeting component by writing:

class Greeting extends React.Component {
  render() {
    const { text, match: {params} } = this.props;
    const { name } = params;

    return (
      <>
        <p>
          {text} {name}
        </p>
      </>
    );
  }
}

We pas in props from the parameter to the Greeting component.

Then we get the props from the this.props property in Greetings .

Then we can do whatever we want with it.

Rerender View on Browser Resize

We can watch for window resize with a hooked if we’re using function components.

For instance, we can write:

import React, { useLayoutEffect, useState } from 'react';

function useWindowSize() {
  const [size, setSize] = useState([0, 0]);
  useLayoutEffect(() => {
    function updateSize() {
      setSize([window.innerWidth, window.innerHeight]);
    }
    window.addEventListener('resize', updateSize);
    updateSize();
    return () => window.removeEventListener('resize', updateSize);
  }, []);
  return size;
}

function App() {
  const [width, height] = useWindowSize();
  return <span>{width} x {height}</span>;
}

We created the useWindowSize hook that watches the window size change by adding an event listener for the resize event.

Then when we return the function to clean up the code, we call removeEventListener to remove the event listener.

We set the size state in the event handler.

The window.innerWidth has the window width and the window.innerHeight has the window height.

Then we can get it the latest values by using our hook in a component.

We create our own hook to encapsulate our logic so that we don’t have to spread them in our code.

Also, we can reuse it anywhere, which is another benefit.

In class components, we can also watch the resize event.

For instance, we can write:

import React from 'react';

class App extends React.Component {
  state = { width: 0, height: 0 };
  render() {
    return <span>{this.state.width} x {this.state.height}</span>;
  }

  updateDimensions = () => {
    this.setState({ width: window.innerWidth, height: window.innerHeight });
  };

  componentDidMount() {
    window.addEventListener('resize', this.updateDimensions);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.updateDimensions);
  }
}

We have the updateDiemsions method to set the window width and height with setState .

Then we call addEventListener in componentDidMount to listen to window size changes.

And we call removeEventListener to remove the listener when the component unmounts.

In the render method, we render the window size.

Fix ‘Uncaught TypeError: Cannot read property ‘setState’ of undefined’ Error

We can fix the setState is undefined error by calling bind on the method that we’re calling in our class component.

For instance, we write:

constructor(props) {
  super(props);
  this.state = {
    count: 1
  };

  this.setCount = this.setCount.bind(this);
}

We call this.setCount.bind(this) to set the value of this of this.setCount to the component.

We call it in the constructor so that we don’t have to call bind multiple times anywhere else.

Also, we can use an arrow function instead.

For instance, we can write:

setCount ` = () => {
  this.setState({
    count : this.state.count + 1
  });
}`

in our component class.

React Router with an Optional Path Parameter

We can add an optional path parameter by adding a question mark to the path parameter.

For instance, we can write:

<Route path="/to/page/:pathParam?" component={Page} />

for one optional parameter.

If we want more, we can write:

<Route path="/to/page/:foo?/:bar?" component={Page} />

This is applicable to version 4 or later.

Setting a Background Image With React Inline Styles

We can set the background image with React inline styles by writing:

backgroundImage: `url(${Background})`

inside the object that we pass into the styles prop.

Backgeround is the image that we imported as a module.

An image can be imported as a module with Webpack.

Conclusion

We can set the background image by import the image as a module and setting that as the value of the background image.

To get the size of the window, we can listen to the resize event.

We can pass props to a route handling component with React Router.

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 *