Categories
React Answers

How to Use Async and Await with Axios in React?

Sometimes, we want to use async and await with Axios in React.

In this article, we’ll look at how to use async and await with Axios in React.

Use Async and Await with Axios in React

To use async and await with Axios in React, we can call axios in an async function.

For instance, we write:

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

export default function App() {
  const [val, setVal] = useState();

  const getAnswer = async () => {
    const { data } = await axios("https://yesno.wtf/api");
    setVal(data.answer);
  };

  useEffect(() => {
    getAnswer();
  }, []);

  return <div>{val}</div>;
}

We call axios with the URL we want to make a GET request to.

It returns a promise that resolves to an object with the data property set to the response data.

So we use await to return the resolved value from the promise.

Then we call setVal with the data.answer property to set the value of val and display that in a div.

Conclusion

To use async and await with Axios in React, we can call axios in an async function.

Categories
React Answers

How to Change the Opacity for a Color in a React Component?

Sometimes, we want to change the opacity for a color in a React component.

In this article, we’ll look at how to change the opacity for a color in a React component.

Change the Opacity for a Color in a React Component

To change the opacity for a color in a React component, we can use the color NPM package.

To install it, we run:

npm i color

Then we can use it by writing:

import React from "react";
import Color from "color";

export default function App() {
  return (
    <div
      style={{
        backgroundColor: Color("red").alpha(0.5).string()
      }}
    >
      hello world
    </div>
  );
}

We call Color with the color name.

And we change the alpha value with the alpha method.

Finally, we return the color code of that color with the string method.

Conclusion

To change the opacity for a color in a React component, we can use the color NPM package.

Categories
React Answers

How to Display Binary Data as Image in React?

Sometimes, we want to display binary data as image in React.

In this article, we’ll look at how to display binary data as image in React.

Display Binary Data as Image in React

To display binary data as image in React, we can convert the image’s binary data to a base64 URL.

Then we can set the src attribute of the img element to the base64 URL.

For instance, we write:

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

const imageUrl =
  "https://i.picsum.photos/id/566/200/300.jpg?hmac=gDpaVMLNupk7AufUDLFHttohsJ9-C17P7L-QKsVgUQU";

export default function App() {
  const [imgUrl, setImgUrl] = useState();

  const getImg = async () => {
    const response = await fetch(imageUrl);
    const imageBlob = await response.blob();
    const reader = new FileReader();
    reader.readAsDataURL(imageBlob);
    reader.onloadend = () => {
      const base64data = reader.result;
      setImgUrl(base64data);
    };
  };

  useEffect(() => {
    getImg();
  }, []);

  return (
    <div>
      <img src={imgUrl} alt="" />
    </div>
  );
}

We have the getImg function that makes a GET request to get an image from the imageUrl with fetch.

Then we call response.blob to convert the binary data response to a blob object.

Next, we create a FileReader instance and call the readAsDataURL method on it with the imageBlob blob object as the argument to convert the data into a base64 URL string.

Finally, we call setImgUrl with the base64 string to set the imgUrl value to the base64 string.

And then we use imgUrl as the value of the img element’s src attribute.

Now we should see the image displayed on the screen.

Conclusion

To display binary data as image in React, we can convert the image’s binary data to a base64 URL.

Then we can set the src attribute of the img element to the base64 URL.

Categories
React Answers

How to Call the useEffect Hook Conditionally with React?

Sometimes, we want to call the useEffect hook conditionally with React.

In this article, we’ll look at how to call the useEffect hook conditionally with React.

Call the useEffect Hook Conditionally with React

To call the useEffect hook conditionally with React, we can check for the condition before running the code in the useEffect callback.

For instance, we write:

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

const wantAnswer = true;

export default function App() {
  const [val, setVal] = useState();

  const getAnswer = async () => {
    const res = await fetch("https://yesno.wtf/api");
    const json = await res.json();
    setVal(json.answer);
  };

  useEffect(() => {
    if (!wantAnswer) {
      return;
    }
    getAnswer();
  }, []);

  return <div>{val}</div>;
}

to call getAnswer only when wantAnswer is true in the useEffect callback.

To do that, we check if wantAnswer is false.

And if it is, we use the return statement to stop running the useEffect callback.

Conclusion

To call the useEffect hook conditionally with React, we can check for the condition before running the code in the useEffect callback.

Categories
React Answers

How to Distinguish Left and Right Click Events in React?

Sometimes, we want to distinguish left and right click events in React.

In this article, we’ll look at how to distinguish left and right click events in React.

Distinguish Left and Right Click Events in React

To distinguish left and right click events in React, we can set the onClick prop and onContextMenu to handle left click and right click events respectively.

For instance, we write:

import React from "react";

export default function App() {
  const handleClick = (e) => {
    if (e.type === "click") {
      console.log("Left click");
    } else if (e.type === "contextmenu") {
      console.log("Right click");
    }
  };

  return (
    <p onClick={handleClick} onContextMenu={handleClick}>
      click me
    </p>
  );
}

to add the handleClick function to handle both left and right click events.

We check which type of click it is with the e.type propety.

If e.type is 'click', then we left clicked on the p element.

And if it’s 'contextmenu', we did a right click.

We can also use the e.nativeEvent.which property to do the same check.

To do this, we write:

import React from "react";

export default function App() {
  const handleClick = (e) => {
    if (e.nativeEvent.which === 1) {
      console.log("Left click");
    } else if (e.nativeEvent.which === 3) {
      console.log("Right click");
    }
  };

  return (
    <p onClick={handleClick} onContextMenu={handleClick}>
      click me
    </p>
  );
}

If e.nativeEvent.which is 1, then we did a left click.

And if it’s 3, then we did a right click.

Conclusion

To distinguish left and right click events in React, we can set the onClick prop and onContextMenu to handle left click and right click events respectively.