Categories
React Tips

React Tips — Watching Props, Downloads, and Media Queries

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.

Run Async Code on Update of State with React Hooks

We can watch for the change of the state with the useEffect hook.

The 2nd argument takes an array that can hold the values that we want to watch.

When they change, the callback in the first argument will run.

For instance, we can write:

function App() {
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (loading) {
      doSomething();
    }
  }, [loading]);

  return (
    <>
      <div>{loading}</div>
      <button onClick={() => setLoading(true)}>click Me</button>
    </>
  );
}

We have the useEffect hook that watches the loading state.

If it changes, then the callback will load.

It’ll change when we click the click me button.

It sets the loading state to true .

How to Download Fetch Response in a React Component as a File

We can download the response retrieved by the Fetch API as a file by converting the result to a blog.

Then we can download it by clicking on an invisible link.

For instance, we can write:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.linkRef = React.createRef();
  }

  componentDidMount() {
    fetch('./file.pdf')
      .then(res => {
        return res.blob();
      }).then(blob => {
        const href = window.URL.createObjectURL(blob);
        const a = this.linkRef.current;
        a.download = 'file.pdf';
        a.href = href;
        a.click();
        a.href = '';
      })
      .catch(err => console.error(err));
  }

  render() {
    return (
      <a ref={this.linkRef}/>
    );
  }
}

We have a link assigned to our ref.

Then with the fetch function, we make a GET request for file.pdf .

Then we convert that to a blob with res.blob()

Once we did that, we pass the blob into the createObjectURL method.

Then we get the link and set the download property to set the file name.

href is set to the object URL we created.

And then we call click to start the download.

And we clear the link by setting href to an empty string.

Updating State with Props on React Child Component

In a child component, we can update the states with props by returning a state in getDerivedStateFromProps.

For instance, we can write:

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    }
  }

  static getDerivedStateFromProps(props) {
    return {
      count: props.count * 2
    }
  }

  // ...
}

We get the count from the props and then we doubled it and return that as the value of the count state.

It’s a static method, unlike most other class component methods.

It’s called every time a component is rendered, regardless of the update.

It’s asynchronous so it’s consistent with other methods, which are also async.

We shouldn’t commit side effects in the method.

If we need to commit side effects, we should do them elsewhere.

Inline CSS Styles in React and Media Queries

We can add CSS styles in the form of inline JavaScrip with the react-responsive package.

It supports adding media queries.

We can install it by running:

npm install react-responsive --save

Then we can write:

import React from 'react'
import { useMediaQuery } from 'react-responsive'

const App  = () => {
  const isDesktopOrLaptop = useMediaQuery({
    query: '(min-device-width: 1224px)'
  })
  const isBigScreen = useMediaQuery({ query: '(min-device-width: 2000px)' })
  const isTablet = useMediaQuery({ query: '(max-width: 1500px)' })
  const isMobile = useMediaQuery({
    query: '(max-device-width: 1000px)'
  })
  const isPortrait = useMediaQuery({ query: '(orientation: portrait)' })

  return (
    <div>
      <p>{isBigScreen && 'big screen'}</p>
      <p>{isTablet && 'tablet screen'}</p>
      <p>{isMobile && 'mobile screen'}</p>
      <p>{isPortrait && 'portrait screen'}</p>
    </div>
  )
}

It comes with th useMediaQuery hook that lets us add media queries for the screen with a given width or orientation.

We have one for the big screen, media query, mobile, and portrait screens.

They all return boolean according to screen size and orientation.

Then we can use them in our JSX code to create responsive layouts.

Conclusion

There are packages for adding media queries with JavaScript.

We can run async code with useEffect .

We can also watch for prop changes and does updates accordingly.

And we can download files in a React component.

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 *