Categories
React Answers

How to get a rendered component height with React?

Sometimes, we want to get a rendered component height with React.

In this article, we’ll look at how to get a rendered component height with React.

How to get a rendered component height with React?

To get a rendered component height with React, we can use the element’s clientHeight property.

For instance, we write:

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

export default function App() {
  const ref = useRef();

  useEffect(() => {
    console.log(ref.current?.clientHeight);
  }, []);

  return <div ref={ref}>hello world</div>;
}

We assign the ref ref to the ref prop of the div.

Then we call useEffect with a callback and an empty array to get the element’s height when the component mounts.

In the useEffect callback, we use ref.current?.clientHeight to get the div’s height in pixels.

Conclusion

To get a rendered component height with React, we can use the element’s clientHeight property.

Categories
React Answers

How to get the value of an input from the input’s ref in a React component?

Sometimes, we want to get the value of an input from the input’s ref in a React component.

In this article, we’ll look at how to get the value of an input from the input’s ref in a React component.

How to get the value of an input from the input’s ref in a React component?

To get the value of an input from the input’s ref in a React component, we can use the value attribute.

For instance, we write:

import React, { useRef } from "react";

export default function App() {
  const cityInput = useRef();

  const onSubmit = (e) => {
    e.preventDefault();
    console.log(cityInput.current.value);
  };

  return (
    <form onSubmit={onSubmit}>
      <input type="text" placeholder="Enter City Name" ref={cityInput} />
      <button>Go!</button>
    </form>
  );
}

We create a cityInput ref with the useRef hook.

Then we define the onSubmit function that gets the input’s value by using cityInput.current.value.

We call e.preventDefault to stop the default server side submission behavior.

Next, we set the ref prop of the input to cityInput so that cityInput.current is set to the input element.

Finally, we set the onSubmit prop to onSubmit to run it when we click Go.

Conclusion

To get the value of an input from the input’s ref in a React component, we can use the value attribute.

Categories
React Answers

How to get select element’s value in react-bootstrap?

Sometimes, we want to get select element’s value in react-bootstrap.

In this article, we’ll look at how to get select element’s value in react-bootstrap.

How to get select element’s value in react-bootstrap?

To get select element’s value in react-bootstrap, we can set the onChange prop to a function that gets the selected value.

For instance, we write:

import React, { useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Form } from "react-bootstrap";

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

  return (
    <Form.Select value={val} onChange={(e) => setVal(e.target.value)}>
      <option>Open this select menu</option>
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3">Three</option>
    </Form.Select>
  );
}

We create the val state with the useState hook.

Then we add a select drop down by adding the Form.Select component.

Next, we set onChange of the Form.Select component to a function that calls setVal with e.target.value to set val to the value attribute value of the selected option element.

As a result, we should see the selected value logged when we change the option we select from the drop down.

Conclusion

To get select element’s value in react-bootstrap, we can set the onChange prop to a function that gets the selected value.

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.