Categories
Books Vue 3 Vue 3 Projects

Buy Vue.js 3 By Example Now

Want to learn Vue 3 fast? Vue.js 3 By Example is out now.

Buy it now at https://www.packtpub.com/product/vue-js-3-by-example/9781838826345

Categories
React Answers

How to Add Event Bubbling and Capturing in React?

Sometimes, we want to add event bubbling and capturing in React.

In this article, we’ll look at how to add event bubbling and capturing in React.

Add Event Bubbling and Capturing in React

To add event bubbling and capturing in React, we can add event handlers to handle them.

To handle bubbling, we just add the regular event handlers.

And to handle capturing, we add Capture to the prop name after the event handler’s prop name.

For instance, we add bubbling by writing:

import React from "react";

export default function App() {
  return (
    <div onClick={() => console.log("parent")}>
      <button onClick={() => console.log("child")}>Click me</button>
    </div>
  );
}

We set the onClick prop of the parent div and the button to log 'parent' and 'child' respectively.

Then when we click the button, we see:

child 
parent 

logged in this order.

So we know event bubbling happened since we child element’s event handler is triggered before the parent’s.

To set event propagation to capturing mode, we add Capture to the end of each prop name.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <div onClickCapture={() => console.log("parent")}>
      <button onClickCapture={() => console.log("child")}>Click me</button>
    </div>
  );
}

to set the onClickCapture prop instead of the onClick prop on each element.

Then we see:

parent 
child 

logged in this order.

So we know event capturing happened since we parent element’s event handler is triggered before the child’s.

Conclusion

To add event bubbling and capturing in React, we can add event handlers to handle them.

To handle bubbling, we just add the regular event handlers.

And to handle capturing, we add Capture to the prop name after the event handler’s prop name.

Categories
React Answers

How to Clear an Input Field with React?

Sometimes, we want to clear an input field with React.

In this article, we’ll look at how to clear an input field with React.

Clear an Input Field with React

To clear an input field with React, we can set the value of the value attribute to an empty string.

For instance, we write:

import React, { useState } from "react";

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

  return (
    <div>
      <input type="text" value={val} />
      <button onClick={() => setVal(() => "")}>Reset</button>
    </div>
  );
}

We create the val state with the useState hook.

Then we set the value prop of the input to the val state.

Next we set the onClick prop of the button to a function that calls setVal to an empty string.

Now when we type in something and click Reset, we see the input box emptied.

Conclusion

To clear an input field with React, we can set the value of the value attribute to an empty string.

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.