Categories
React Answers

How to Get Input Text Field Values When Enter Key is Pressed in React?

Sometimes, we want to get input text field values when enter key is pressed in React.

In this article, we’ll look at how to get input text field values when enter key is pressed in React.

Get Input Text Field Values When Enter Key is Pressed in React

To get input text field values when enter key is pressed in React, we can add an event handler for the keypress event into the input.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <input
      onKeyPress={(ev) => {
        if (ev.key === "Enter") {
          ev.preventDefault();
          console.log(ev.target.value);
        }
      }}
    />
  );
}

to set the onKeyPress prop to a function that checks if the enter key is pressed by comparing 'Enter' against ev.key.

We prevent the default server side form submission behavior from happening with ev.preventDefault.

If it’s true. then we get the value that’s typed into the input box with ev.target.value.

Conclusion

To get input text field values when enter key is pressed in React, we can add an event handler for the keypress event into the input.

Categories
React Answers

How to Handle Double Click Events in a React Component?

Sometimes, we want to handle double click events in a React component.

In this article, we’ll look at how to handle double click events in a React component.

Handle Double Click Events in a React Component

To handle double click events in a React component, we can use the regular click event handler and check how many clicks are done with the detail property.

For instance, we write:

import React from "react";

export default function App() {
  const handleClick = (e) => {
    switch (e.detail) {
      case 1:
        console.log("click");
        break;
      case 2:
        console.log("double click");
        break;
      case 3:
        console.log("triple click");
        break;
      default:
        return;
    }
  };

  return <button onClick={handleClick}>Click me</button>;
}

We have the handleClick function that checks the e.detail property to see how many clicks are done.

If it’s 2, then we know the user double clicked.

When we double click on the button, we should see 'double click' logged in the console.

Conclusion

To handle double click events in a React component, we can use the regular click event handler and check how many clicks are done with the detail property.

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.