Blur an Image

Create a slider to control an image’s blur.


Environment

Use the environment you are most comfortable with. I recommend using create-react-app to create a local version of the project so that you can inspect the DOM easily from your browser when debugging. Alternatively, you can work from a blank React template in CodeSandbox. Starter code is provided after the problem specification.

Specification

In this challenge, we will rely on the API provided by Lorem Picsum, created by David Marby and Nijiko Yonskai. The documentation (including all that you will need for this challenge) can be found on the homepage.

Write a functional component called CustomBlur to render an image from Lorem Picsum. Below it, include a slider that allows the user to adjust the blur effect on the image. If you use the native img element as I do in the solution below, be sure to include a seed in the image so that the image is not replaced as the blur parameter changes. The constant base URL included in the starter code uses “sameimage” as the seed.

Starter Code

Here is some code to get you started:

import React, { useEffect, useState } from "react";

const BASE_IMG_URL = "https://picsum.photos/seed/sameimage/300";

function App() {
  return <CustomBlur />;
}

const CustomBlur = () => {
  // YOUR CODE HERE
};

export default App;

Solution

import React, { useEffect, useState } from "react";

const BASE_IMG_URL = "https://picsum.photos/seed/sameimage/300";

function App() {
  return <CustomBlur />;
}

const CustomBlur = () => {
  const [image, setImage] = useState(BASE_IMG_URL);
  const [blur, setBlur] = useState(0);

  useEffect(() => {
    setImage(blur != 0 ? BASE_IMG_URL + "?blur=" + blur : BASE_IMG_URL);
  }, [blur]);

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
      }}
    >
      <img src={image} width={300} height={300} style={{ margin: 60 }} />
      <p1>Slide to blur</p1>
      <input
        type="range"
        step="1"
        min="0"
        max="10"
        value={blur}
        onChange={(e) => setBlur(e.target.value)}
      />
    </div>
  );
};

export default App;

I first initialize two state variables, one to store the image URL and another for the value of the blur slider. We set up an effect using the useEffect() hook to update the URL when the slider changes. Importantly, we revert to the base URL when the slider is moved back to 0. The blur parameter must be an integer between 1 and 10, and the server returns an error instead of an image if an invalid parameter is passed.

For an additional challenge, extend your UI to enable the user to adjust the other parameters supported by Lorem Picsum.


useState
useEffect