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.

Categories
React Answers

How to Put a File in a State Variable with React Hooks?

Sometimes, we want to put a file in a state variable with React Hooks.

In this article, we’ll look at how to put a file in a state variable with React Hooks.

Put a File in a State Variable with React Hooks

We can put a file in a state variable with the useState hook.

For instance, we can write:

import React, { useState } from "react";

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

  return (
    <div className="App">
      <input
        type="file"
        onChange={(e) => {
          const [file] = e.target.files;
          setPicture((picture) => [...picture, file]);
        }}
      />
    </div>
  );
}

We define the picture state with the useState hook.

Then we add a file input by setting the type attribute of the input to file .

And then we add an onChange callback that takes the selected file from e.target.files with destructuring.

Then we call setPicture with a callback that takes the existing picture state value and return a new array with the picture items spread into it and the newly selected file .

Now when we select files with the file input, pictures should log an array with all the selected files.

Conclusion

We can put a file in a state variable with the useState hook.

Categories
React Answers

How to Cache Computed Values with the React useMemo Hook?

We can use the React useMemo hook to cache computed values.

In this article, we’ll look at how to use the React useMemo hook to cache computed values.

Memoize Values with the React useMemo Hook

We can also use the useMemo hook to create a memoized values, which means that it’s cached as long as it or its dependencies don’t change.

useMemo runs during rendering. Therefore, we shouldn’t run anything that we wouldn’t do during rendering.

It’s used as a performance optimization, but it’s not a guarantee of the integrity of the value because it might change later.

For instance, we can use it as follows:

import React from "react";

export default function App() {
  const [firstName, setFirstName] = React.useState("");
  const [lastName, setLastName] = React.useState("");
  const name = React.useMemo(() => `${firstName} ${lastName}`, [
    firstName,
    lastName
  ]);

  return (
    <div>
      <input value={firstName} onChange={e => setFirstName(e.target.value)} />
      <input value={lastName} onChange={e => setLastName(e.target.value)} />
      <p>{name}</p>
    </div>
  );
}

In the code above, we used useMemo to watch firstName and lastName ‘s values and then derive a new value name from combining the 2.

Then when we enter text into the input, we’ll see that it updates the value of name . However, it’ll cache the existing value if firstName or lastName don’t change.

Conclusion

We can also use the useMemo hook to create a memoized values, which means that it’s cached as long as it or its dependencies don’t change.