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.

Categories
React Answers

How to Fix the “Uncaught TypeError: Cannot read property ‘push’ of undefined” Error When Developing Apps with React Router?

Sometimes, we may run into the "Uncaught TypeError: Cannot read property ‘push’ of undefined" error when developing apps with React Router.

In this article, we’ll look at how to fix the "Uncaught TypeError: Cannot read property ‘push’ of undefined" error when developing apps with React Router.

Fix the "Uncaught TypeError: Cannot read property ‘push’ of undefined" Error When Developing Apps with React Router

To fix the "Uncaught TypeError: Cannot read property ‘push’ of undefined" error when developing apps with React Router, we can get the history object from the useHistory hook.

For instance, we write:

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  NavLink,
  useHistory
} from "react-router-dom";

const Foo = () => {
  return <p>foo</p>;
};

const Bar = () => {
  const history = useHistory();
  return (
    <>
      <p>bar</p>
      <p onClick={() => history.push("/foo")}>foo</p>
    </>
  );
};

export default function App() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <NavLink to="/foo">foo</NavLink>
          </li>
          <li>
            <NavLink to="/bar">bar</NavLink>
          </li>
        </ul>

        <Switch>
          <Route path="/foo" children={<Foo />} />
          <Route path="/bar" children={<Bar />} />
        </Switch>
      </div>
    </Router>
  );
}

In the Bar component, we call useHistory to return the history object and assign it to history.

Then we call history.push in the function we set as the value of the onClick prop to go to the /foo page.

We can only call this inside route components and their children.

Otherwise, we’ll get the "Uncaught TypeError: Cannot read property ‘push’ of undefined" again.

Conclusion

To fix the "Uncaught TypeError: Cannot read property ‘push’ of undefined" error when developing apps with React Router, we can get the history object from the useHistory hook.

We can only call this inside route components and their children.

Categories
React Answers

How to Render Multiple React Components in a React Component?

Sometimes, we want to render multiple React components in a React component.

In this article, we’ll look at how to render multiple React components in a React component.

Render Multiple React Components in a React Component

To render multiple React components in a React component, we can render an array of components or we can render multiple components inside a fragment.

For instance, we write:

import React from "react";

const Foo = () => <div>foo</div>;

const Bar = () => <div>bar</div>;

export default function App() {
  return [<Foo />, <Bar />];
}

to render Foo and Bar together by putting them in an array.

To render them in a fragment, we write:

import React from "react";

const Foo = () => <div>foo</div>;

const Bar = () => <div>bar</div>;

export default function App() {
  return (
    <>
      <Foo />
      <Bar />
    </>
  );
}

or:

import React from "react";

const Foo = () => <div>foo</div>;

const Bar = () => <div>bar</div>;

export default function App() {
  return (
    <React.Fragment>
      <Foo />
      <Bar />
    </React.Fragment>
  );
}

Conclusion

To render multiple React components in a React component, we can render an array of components or we can render multiple components inside a fragment.