Categories
React Answers

How to use the useCallback hook for map rendering with React?

Sometimes, we want to use the useCallback hook for map rendering with React.

In this article, we’ll look at how to use the useCallback hook for map rendering with React.

How to use the useCallback hook for map rendering with React?

To use the useCallback hook for map rendering with React, we can pass in the function we want to update when a state or prop updates as the useCallback callback.

For instance, we write:

import React, { useCallback } from "react";

const ExpensiveComponent = ({ onEvent }) => {
  //...
  return <p>expensive</p>;
};

const MappedComponent = ({ id }) => {
  const onEvent = useCallback(() => console.log(id), []);
  return <ExpensiveComponent onEvent={onEvent} />;
};

const FrequentlyRerendersMap = ({ ids }) => {
  return ids.map((id) => {
    return <MappedComponent key={id} id={id} />;
  });
};

export default function App() {
  return <FrequentlyRerendersMap ids={[1, 2, 3]} />;
}

We have the ExpensiveComponent that takes the onEvent function prop.

Then we define the MappedComponent that defines the onEvent function which is defined with the useCallback hook with a callback.

Then callback is run when onEvent is called.

Next, we have the FrequentlyRerendersMap component that renders an array of MappedComponent with the ids.map method.

Finally, we render FrequentlyRerendersMap in App.

Conclusion

To use the useCallback hook for map rendering with React, we can pass in the function we want to update when a state or prop updates as the useCallback callback.

Categories
React Answers

How to store the state of radio groups in React using react-hook-form?

Sometimes, we want to store the state of radio groups in React using react-hook-form.

In this article, we’ll look at how to store the state of radio groups in React using react-hook-form.

How to store the state of radio groups in React using react-hook-form?

To store the state of radio groups in React using react-hook-form, we can set the defaultChecked prop to the initial checked value for each radio button.

For instance, we write:

import React, { useState } from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const [state] = useState({ data: { checked: "1" } });
  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm();
  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="vehicles">
        How many vehicles do you own?
        <br />
        <input
          type="radio"
          name="vehicles"
          value="1"
          {...register("vehicles", { required: true })}
          className="radio"
          defaultChecked={state.data.checked === "1"}
        />
        <label>1</label>
        <input
          type="radio"
          name="vehicles"
          value="2"
          {...register("vehicles", { required: true })}
          className="radio"
          defaultChecked={state.data.checked === "2"}
        />
        <label>2</label>
        {errors.vehicles && (
          <div className="form_error">Number of Vehicles is required</div>
        )}
      </label>

      <input type="submit" />
    </form>
  );
}

We use the useForm hook to return an object with various properties we use to create our form.

Next, we define the onSubmit function that we use as the form submit handler.

Then we add our form element with the onSubmit prop set to handleSubmit(onSubmit) which only runs when the form values are all valid.

Next, we add inputs that we register as react-hook-form fields with register.

And we set the defaultChecked prop to set the condition for which the radio button is checked.

The initial checked value is checked according to the initial state value.

Therefore, 1 should be selected initially.

Conclusion

To store the state of radio groups in React using react-hook-form, we can set the defaultChecked prop to the initial checked value for each radio button.

Categories
React Answers

How to add a PowerPoint viewer into a React component?

Sometimes, we want to add a PowerPoint viewer into a React component.

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

How to add a PowerPoint viewer into a React component?

To add a PowerPoint viewer into a React component, we can add a iframe that shows the PowerPoint slide’s with Microsoft’s online PowerPoint viewer.

For instance, we write:

import React from "react";

const linkToPPTFile =
  "https://scholar.harvard.edu/files/torman_personal/files/samplepptx.pptx";

export default function App() {
  return (
    <>
      <iframe
        src={`https://view.officeapps.live.com/op/embed.aspx?src=${linkToPPTFile}`}
        width="100%"
        height="600px"
        frameBorder="0"
        title="slides"
      ></iframe>
    </>
  );
}

We want to show the PowerPoint presentation that’s located in the URL assigned to linkToPPTFile .

To show the slides, we add an iframe with src set to https://view.officeapps.live.com/op/embed.aspx?src=${linkToPPTFile}.

We also set the width and height to set the dimensions.

And we set the frameBorder to 0 to remove the iframe border.

Conclusion

To add a PowerPoint viewer into a React component, we can add a iframe that shows the PowerPoint slide’s with Microsoft’s online PowerPoint viewer.

Categories
React Answers

How to create a number input with no negative, decimal, or zero value values with React?

Sometimes, we want to create a number input with no negative, decimal, or zero value values with React.

In this article, we’ll look at how to create a number input with no negative, decimal, or zero value values with React.

How to create a number input with no negative, decimal, or zero value values with React?

To create a number input with no negative, decimal, or zero value values with React, we can create our own input component.

For instance, we write:

import React, { useState } from "react";

const PositiveInput = () => {
  const [value, setValue] = useState("");

  const onChange = (e) => {
    const value = e.target.value.replace(/[^\d]/, "");

    if (+value !== 0) {
      setValue(value);
    }
  };

  return <input type="text" value={value} onChange={onChange} />;
};

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

We create the PositiveInput component that lets us only enter positive numbers.

In the component, we have the value state.

And we define the onChange function that sets the value state by getting the value from the input.

And we replace all the non numerical values in the input value with empty strings.

This is done with const value = e.target.value.replace(/[^\d]/, "");.

Then if value isn’t 0, then we call setValue to set value.

Next, we set the value prop of the input to value and the onChange prop to onChange.

Finally, we add the input to App.

Conclusion

To create a number input with no negative, decimal, or zero value values with React, we can create our own input component.

Categories
React Answers

How to fix the newlines character ignored by JSX tables issue with React?

Sometimes, we want to fix the newlines character ignored by JSX tables issue with React.

In this article, we’ll look at how to fix the newlines character ignored by JSX tables issue with React.

How to fix the newlines character ignored by JSX tables issue with React?

To fix the newlines character ignored by JSX tables issue with React, we can set the white-space CSS property to pre in the cell.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <>
      <style>
        {`.pre-wrap {
          white-space: pre-wrap
        }`}
      </style>
      <table>
        <tbody>
          <tr>
            <td className="pre-wrap">
              {
                "Line 1\nLine 2\nLine 3\nThis is a cell with white-space: pre-wrap"
              }
            </td>
          </tr>
        </tbody>
      </table>
    </>
  );
}

We have a string that have some new line characters between a few substrings.

To make them display in separate lines, we add the pre-wrap class which sets the white-space CSS property to pre-wrap.

And we set the className of the td to pre-wrap to apply the styles.

Now we should see that each line in the string are displayed on separate lines.

Conclusion

To fix the newlines character ignored by JSX tables issue with React, we can set the white-space CSS property to pre in the cell.