Categories
React Answers

How to Delete an Item from a State Array in a React Component?

Sometimes, we want to delete an item from a state array in a React component.

In this article, we’ll look at how to delete an item from a state array in a React component.

Delete an Item from a State Array in a React Component

We can return a new array within the state setter function’s callback to change a React component’s state array.

For instance, we can write:

import React, { useState } from "react";

export default function App() {
  const [names, setNames] = useState(["jane", "john", "james"]);

  return (
    <div className="App">
      <button
        onClick={() =>
          setNames((names) => names.filter((_, i) => i !== names.length - 1))
        }
      >
        delete
      </button>
      <div>{names.join(", ")}</div>
    </div>
  );
}

We have the names state array that we created with useState .

Then we have a button that has the onClick prop set to a function that calls setNames with a callback that returns the names array without the last element.

We remove the last element from the returned array by calling filter with a callback that checks whether i isn’t names.length — 1 .

This will update the names array with the array returned by filter .

And below that, we render the names entries in a string.

Now when we click on the button, we see the last name in the string removed.

Conclusion

We can return a new array within the state setter function’s callback to change a React component’s state array.

Categories
React Answers

How to Scroll to an Element in a React Component?

Sometimes, we want to scroll to an element in a React component.

In this article, we’ll look at how to scroll to an element in a React component.

Scroll to an Element in a React Component

We can scroll to an element by assigning a ref to it and calling scrollIntoView on it.

For instance, we can write:

import React, { useRef } from "react";

export default function App() {
  const myRef = useRef(null);

  const executeScroll = () => myRef.current.scrollIntoView();

  return (
    <>
      <button onClick={executeScroll}> Click to scroll </button>
      {Array(100)
        .fill()
        .map((_, i) => (
          <p>{i}</p>
        ))}
      <div ref={myRef}>Element to scroll to</div>
    </>
  );
}

We create myRef with the useRef hook,

Then we create the executeScroll method that calls scrollIntoView on the element that’s been assigned the ref.

myRef.current has the element we assigned the ref to as its value.

We assign the ref by assigning the ref prop with myRef .

Then we set the onClick prop to executeScroll to run executeScroll when we click on the button.

Now when we click on the button, we should scroll to the element that’s assigned to myRef .

Conclusion

We can scroll to an element by assigning a ref to it and calling scrollIntoView on it.

Categories
React Answers

How to Render an HTML String within a React Component?

Sometimes, we want to render an HTML string in a React component.

In this article, we’ll look at how to render an HTML string in a React component.

Render an HTML String within a React Component with the dangerouslySetInnerHTML Prop

We can use the dangerouslySetInnerHTML prop to render an HTML string onto the screen.

For instance, we can write:

import React from "react";

export default function App() {
  const articleContent = "<p><b>Lorem ipsum dolor laboriosam.</b></p>";

  return (
    <div className="App">
      <div dangerouslySetInnerHTML={{ __html: articleContent }} />
    </div>
  );
}

to add the dangerouslySetInnerHTML with an object with the __html property set to the articleContent HTML string as its value.

Then we see the HTML rendered as is without escaping.

Conclusion

We can use the dangerouslySetInnerHTML prop to render an HTML string onto the screen.

Categories
React Answers

How to Pass a Value to the onClick Callback in a React Component?

Sometimes, we want to pass a value to the onClick callback in our React component.

In this article, we’ll look at how to pass a value to the onClick callback in our React component.

Pass a Value to the onClick Callback in a React Component

One way to pass a value to the onClick callback is to pass in a function that calls another function into the onClick prop.

For instance, we can write:

import React from "react";

export default function App() {
  const onClick = (val) => {
    console.log(val);
  };

  return (
    <div className="App">
      <button onClick={() => onClick("clicked")}>click me</button>
    </div>
  );
}

We pass in:

() => onClick("clicked")

as the value of onClick .

This will run the onClick function when we click the button with 'value' passed in.

And we see that logged when we click on the button.

This will create a new function on every render.

A more efficient way to achieve the same result would be to create a function outside the onClick prop and pass it in.

To do this, we write:

import React from "react";

export default function App() {
  const onClick = (val) => (e) => {
    console.log(val);
  };

  return (
    <div className="App">
      <button onClick={onClick("clicked")}>click me</button>
    </div>
  );
}

We change the onClick function to take the val value and return a function with the click handler that logs val .

And then we pass the function returned by onClick as the value of the onClick prop.

This is more efficient since the onClick callback won’t be created new on every render.

Conclusion

One way to pass a value to the onClick callback is to pass in a function that calls another function into the onClick prop.

A more efficient way to achieve the same result would be to create a function outside the onClick prop and pass it in.

Categories
React Answers

How to Display JSON Output Using React?

Sometimes, we want to display JSON output in our React components.

In this article, we’ll look at how to display JSON output in our React components.

Display JSON Output Using React with the JSON.stringify Method

We can display JSON output in our React components with the JSON.stringify method.

For instance, we can write:

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

export default function App() {
  const [json, setJson] = useState({});

  const getJSON = async () => {
    const res = await fetch("https://yesno.wtf/api");
    const data = await res.json();
    setJson(data);
  };

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

  return <div className="App">{JSON.stringify(json)}</div>;
}

to create the json state with the useState hook.

Then we create the getJSON function to call fetch to get the JSON data we want to display.

We call res.json to turn the JSONM response string into a JavaScript object.

Then we call setJson to set data as the value of the json state.

Next, we have the useEffect hook to run getJSON when the component mounts.

And then in the JSX, we call JSON.stringify to stringify the json object so that we can render it on the screen.

We can only render strings or JSX on the screen.

Conclusion

We can display JSON output in our React components with the JSON.stringify method.