Categories
React Answers

How to Listen to the Drop Down’s Change Event in React?

Sometimes, we want to listen to the drop down’s change event in React.

In this article, we’ll look at how to listen to the drop down’s change event in React.

Listen to the Drop Down’s Change Event in React

To listen to the drop down’s change event in React, we can set the onChange prop of the select element to the change event listener function.

For instance, we write:

import React, { useState } from "react";

const Dropdown = ({ options }) => {
  const [selectedOption, setSelectedOption] = useState(options[0].value);
  return (
    <select
      value={selectedOption}
      onChange={(e) => setSelectedOption(e.target.value)}
    >
      {options.map((o) => (
        <option key={o.value} value={o.value}>
          {o.label}
        </option>
      ))}
    </select>
  );
};

const options = [
  { value: "apple", label: "Apple" },
  { value: "orange", label: "Orange" },
  { value: "pear", label: "Pear" }
];

export default function App() {
  return <Dropdown options={options} />;
}

to define the Dropdown component that takes an array of options.

In the component, we define the selectedOption state, which is set to options[0].value initially, which is the value of the first option.

Then we set selectedOption as the value prop’s value.

And we set onChange to a function that calls setSelectedOption with e.target.value to set selectedOption to the value attribute’s value of the selected option.

In the select element, we render the option elements from the options array.

Finally, in App, we add the Dropdown component and set options to an options array.

Conclusion

To listen to the drop down’s change event in React, we can set the onChange prop of the select element to the change event listener function.

Categories
React Answers

How to Access Custom Attributes from an Event Object in React?

Sometimes, we want to access custom attributes from an event object in React.

In this article, we’ll look at how to access custom attributes from an event object in React.

Access Custom Attributes from an Event Object in React

To access custom attributes from an event object in React, we can use the e.currentTarget.dataset property.

For instance, we write:

import React from "react";

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

  return (
    <button data-tag="Tag Value" onClick={onClick}>
      Click me
    </button>
  );
}

We have the e.currentTarget.dataset.tag property to access the value of the data-tag attribute of the element we clicked on in the onClick function.

Then we assign the onClick function as the value of the onClick prop of the button.

And we set the data-tag attribute to Tag Value.

Now when we click on the button, we should see the data-tag attribute value logged in the console.

Conclusion

To access custom attributes from an event object in React, we can use the e.currentTarget.dataset property.

Categories
React Answers

How to Fix the “TypeError [ERR_INVALID_ARG_TYPE]: The “path” argument must be of type string. Received type undefined” Error When Starting a React App?

Sometimes, we may run into the "TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined" error when starting a React app.

In this article, we’ll look at how to fix the "TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined" error when starting a React app.

Fix the "TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined" Error When Starting a React App

To fix the "TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined" error when starting a React app, we should upgrade the react-scripts package to the latest version.

To do this, we:

  1. Replace in your package.json "react-scripts": "^3.x.x" with "react-scripts": "^3.4.1" (or the latest available version) (optional for some)
  2. Delete the node_modules folder in the project.
  3. Run npm install or yarn install

This error may be caused by running npm audit fix, so avoid running this command to avoid this error.

Conclusion

To fix the "TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined" error when starting a React app, we should upgrade the react-scripts package to the latest version.

Categories
React Answers

How to Fix the ‘Maximum update depth exceeded error’ When Developing React Apps?

Sometimes, we may run into to fix the ‘Maximum update depth exceeded error’ when developing React apps.

In this article, we’ll look at how to fix the ‘Maximum update depth exceeded error’ when developing React apps.

Fix the ‘Maximum update depth exceeded error’ When Developing React Apps

To fix the ‘Maximum update depth exceeded error’ when developing React apps, we should make sure no code is keeping the component from re-rendering without stopping.

One common source of the error is that we called a function when we pass in a prop instead of passing in a function reference.

For instance, instead of writing:

{<td><span onClick={toggle()}>Details</span></td>}

We should write:

{<td><span onClick={toggle}>Details</span></td>}

so that toggle is called only when we click on the span.

Conclusion

To fix the ‘Maximum update depth exceeded error’ when developing React apps, we should make sure no code is keeping the component from re-rendering without stopping.

One common source of the error is that we called a function when we pass in a prop instead of passing in a function reference.

Categories
React Answers

How to Initialize State from Props in a React Component?

Sometimes, we want to initialize state from props in a React component.

In this article, we’ll look at how to initialize state from props in a React component.

Initialize State from Props in a React Component

To initialize state from props in a React component, we can watch the prop’s value with the useEffect hook, then we can call the state setter function to set the state’s value to the prop’s value.

For instance, we write:

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

const Child = ({ text }) => {
  const [val, setVal] = useState();
  useEffect(() => {
    setVal(text);
  }, [text]);

  return <div>{val}</div>;
};

export default function App() {
  return <Child text="hello world" />;
}

to create the Child component with the text prop.

We create the val state with the useState hook.

Then we call the useEffect hook with a callback that calls setVal with text.

The 2nd argument is set to an array with text so that we watch for changes in the text prop.

And then we render val in the div.

In App, we add the Child component and set the text prop.

Therefore, we should see ‘hello world’ rendered.

Conclusion

To initialize state from props in a React component, we can watch the prop’s value with the useEffect hook, then we can call the state setter function to set the state’s value to the prop’s value.