Categories
React Answers

How to add a Leaflet map into a React component?

Sometimes, we want to add a Leaflet map into a React component.

In this article, we’ll look at how to add a Leaflet map into a React component.

How to add a Leaflet map into a React component?

To add a Leaflet map into a React component, we can use the React Leaflet library.

To install it, we run:

npm i leaflet react-leaflet

Then we can add a map by writing:

import React from "react";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";

const position = [51.505, -0.09];

export default function App() {
  return (
    <MapContainer
      style={{ height: "300px" }}
      center={position}
      zoom={13}
      scrollWheelZoom={false}
    >
      <TileLayer
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      <Marker position={position}>
        <Popup>
          A pretty CSS3 popup. <br /> Easily customizable.
        </Popup>
      </Marker>
    </MapContainer>
  );
}

And we add the Leaflet CSS to the index.html file:

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
   integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
   crossorigin=""/>

We add the MapContainer with the defined height so that Leaflet can render the map properly.

Also, set set the center prop to the latitude and longitude of the center of the map.

zoom sets the default zoom level.

scrolLWheelZoom lets us zoom the map with the scroll wheel if it’s true.

We use the TileLayer component to add a map layer.

And we use Marker to add a marker.

The Popup component lets us display a popup when we click on a marker.

Now we should see a map displayed.

Conclusion

To add a Leaflet map into a React component, we can use the React Leaflet library.

Categories
React Answers

How to fetch image from API with React?

Sometimes, we want to fetch image from API with React.

In this article, we’ll look at how to fetch image from API with React.

How to fetch image from API with React?

To fetch image from API with React, we can use the fetch function.

For instance, we write:

import React, { useEffect, useState } from "react";
const imageUrl = "https://i.imgur.com/fHyEMsl.jpg";

export default function App() {
  const [img, setImg] = useState();

  const fetchImage = async () => {
    const res = await fetch(imageUrl);
    const imageBlob = await res.blob();
    const imageObjectURL = URL.createObjectURL(imageBlob);
    setImg(imageObjectURL);
  };

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

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

We call fetch with the imageUrl to make a GET request to it.

Then we call res.blob to convert the response object to a blob.

Next, we call URL.createObjectURL with the imageBlob to convert it to a URL string that we can set as the src attribute of the img element.

Finally, we call setImg with imageObjectURL so we can set img as the value of src to display it.

Conclusion

To fetch image from API with React, we can use the fetch function.

Categories
React Answers

How to use if statements within a map callback in React?

Sometimes, we want to use if statements within a map callback in React.

In this article, we’ll look at how to use if statements within a map callback in React.

How to use if statements within a map callback in React?

To use if statements within a map callback in React, we can put the if statements inside the map callback and return the items we want according to the given condition.

For instance, we write:

import React from "react";

const nums = [1, 2, 3, 4, 5, 6];

export default function App() {
  return (
    <>
      {nums.map((n) => {
        if (n % 2 === 0) {
          return (
            <p key={n} style={{ color: "green" }}>
              {n}
            </p>
          );
        } else {
          return (
            <p key={n} style={{ color: "red" }}>
              {n}
            </p>
          );
        }
      })}
    </>
  );
}

We call nums.map with a callback that checks if n is even with n % 2 === 0.

If it is, we return a p element with green text.

Otherwise, we return a p element with red text.

We set the key element of the component we return to a unique value so React can keep track of the items.

Conclusion

To use if statements within a map callback in React, we can put the if statements inside the map callback and return the items we want according to the given condition.

Categories
React Answers

How to add pseudo selector inline styling to the styles prop with React?

Sometimes, we want to add pseudo selector inline styling to the styles prop with React.

In this article, we’ll look at how to add pseudo selector inline styling to the styles prop with React.

How to add pseudo selector inline styling to the styles prop with React?

To add pseudo selector inline styling to the styles prop with React, we can use the Radium library.

For instance, we write:

import React from "react";
import Radium from "radium";

const style = {
  color: "#000000",
  ":hover": {
    color: "#ffffff"
  }
};

const MyComponent = () => {
  return <section style={style}>hello world</section>;
};

const MyStyledComponent = Radium(MyComponent);

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

We set the style object we the value of the style prop in MyComponent to add the hover styles to the section element.

Then we call the Radium HOC with MyComponent to create the MyStyledComponent component with the hover styles.

Finally, we use MyStyledComponent in App and we can see that the section element’s content becomes white when we hover over it.

Conclusion

To add pseudo selector inline styling to the styles prop with React, we can use the Radium library.

Categories
React Answers

How to pass an array to useEffect dependency list in React?

Sometimes, we want to pass an array to useEffect dependency list in React.

In this article, we’ll look at how to pass an array to useEffect dependency list in React.

How to pass an array to useEffect dependency list in React?

To pass an array to useEffect dependency list in React, we can pass in the array state into the dependencies list.

For instance, we write:

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

export default function App() {
  const [nums, setNums] = useState([]);

  useEffect(() => {
    console.log(nums);
  }, [nums]);

  return (
    <>
      <button onClick={() => setNums((nums) => [...nums, nums.length + 1])}>
        insert number
      </button>
      <p>{JSON.stringify(nums)}</p>
    </>
  );
}

We have the nums array state we created with the useState hook.

Then we call useEffect with a callback that logs the current value of nums.

We watch the value of the nums array by passing it into the dependencies array.

Finally, we have a button that inserts a number into nums when we click it.

Now we should see the nums state logged when we click on the button.

Conclusion

To pass an array to useEffect dependency list in React, we can pass in the array state into the dependencies list.