Categories
React Answers

How to Fix the ‘Special Props Warning’ When Developing React Apps?

Sometimes, we may run into the ‘Special Props Warning’ when we’re developing React apps.

In this article, we’ll look at how to fix the ‘Special Props Warning’ when we’re developing React apps.

Fix the ‘Special Props Warning’ When Developing React Apps

To fix the ‘Special Props Warning’ when we’re developing React apps, we shouldn’t accessing special props in our React components.

Special React component props includes the key and ref props.

They aren’t passed into the component.

For instance, we shouldn’t write code like:

const Foo = ({ ref }) => {
  return <Comp foo={ref} />;
};

or

const Foo = ({ key }) => {
  return <Comp foo={key} />;
};

since ref and key are special props that can’t be accessed by the component that’s receiving the props.

If we need to pass in values to the prop, we shouldn’t use key or ref as prop names.

Instead, we write something like:

const Foo = ({ id }) => {
  return <Comp foo={id} />;
};

const Bar = () => {
  return <Foo id={1} />;
};

which do not attempt to access those props in any component code.

Conclusion

To fix the ‘Special Props Warning’ when we’re developing React apps, we shouldn’t accessing special props in our React components.

Special React component props includes the key and ref props.

They aren’t passed into the component.

Categories
React Answers

How to Fix the ‘Unknown Prop Warning’ When Developing React Apps?

Sometimes, we may run into the ‘Unknown Prop Warning’ when developing React apps.

In this article, we’ll look at how to fix the ‘Unknown Prop Warning’ when developing React apps.

Fix the ‘Unknown Prop Warning’ When Developing React Apps

To fix the ‘Unknown Prop Warning’ when developing React apps, we should make sure that we’re passing in props to an element that are recognized as valid attributes.

For instance, if we have:

const Foo = (props) => {
  if (props.layout === 'horizontal') {
    return <div {...props} style={getHorizontalStyle()} />
  } else {
    return <div {...props} style={getVerticalStyle()} />
  }
}

Then we all the properties of props as props of the div element.

This means that the layout prop is also passed in as a prop of the div.

However, layout is not a valid attribute of the div, so we’ll get the ‘unknown prop’ warning in the console as a result.

To make sure we’re only passing in valid properties to the divs, we should destructure the props, we want to pass in.

For instance, we can write:

const Foo = ({ layout, ...rest }) => {
  if (layout === "horizontal") {
    return <div {...rest} style={getHorizontalStyle()} />;
  } else {
    return <div {...rest} style={getVerticalStyle()} />;
  }
};

to use the rest syntax to of the rest object that excludes the layout property.

Then we can spread the rest object properties as props of the div.

Assuming rest property names are all valid attribute names, we shouldn’t get the warning anymore.

Conclusion

To fix the ‘Unknown Prop Warning’ when developing React apps, we should make sure that we’re passing in props to an element that are recognized as valid attributes.

Categories
React Answers

How to Retrieve Values from a Select Element with Multiple Options in React?

Sometimes, we want to retrieve values from a select element with multiple options in React.

In this article, we’ll look at how to retrieve values from a select element with multiple options in React.

Retrieve Values from a Select Element with Multiple Options in React

To retrieve values from a select element with multiple options in React, we can get the selected values from the e.target.selectedOptions property.

For instance, we can write:

import { useState } from "react";

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

  const handleChange = (e) => {
    const value = Array.from(
      e.target.selectedOptions,
      (option) => option.value
    );
    setVal(value);
  };

  return (
    <div className="App">
      <select multiple value={val} onChange={handleChange}>
        <option value={1}>First option</option>
        <option value={2}>Second option</option>
        <option value={3}>Third option</option>
      </select>
    </div>
  );
}

We create the val state to store the selected values with the useState hook.

Then we create the handleChange function to get the values from the e.target.selectedOptions by calling Array.from with a callback to map them to the value of each option selected.

e.target.selectedOptions has the selected options.

We then call setVal with value to set val to value .

Then finally, we add the select element with the multiple prop to let us pick multiple options.

We also set the value prop to val to let us see the values we selected.

And we set onChange to handleChange to set val to the updated variables.

Conclusion

To retrieve values from a select element with multiple options in React, we can get the selected values from the e.target.selectedOptions property.

Categories
React Answers

How to Add a Click Handler to the Body Element from within a React Component?

Sometimes, we want to add a click handler to the body element from within a React component.

In this article, we’ll look at how to add a click handler to the body element from within a React component.

Add a Click Handler to the Body Element from within a React Component

To add a click handler to the body element from within a React component, we call the addEventListener method on document.body in the useEffect hook callback to starting listening to clicks on the body element when the component loads.

For instance, we can write:

import React, { useEffect } from "react";
export default function App() {
  useEffect(() => {
    const onClick = () => {
      console.log("body clicked");
    };
    document.body.addEventListener("click", onClick);

    return () => {
      document.body.removeEventListener("click", onClick);
    };
  }, []);

  return <div>hello world</div>;
}

to call the useEffect hook with a callback that calls document.body.addEventListener with 'click' and onClick to add the onClick function as the event listener for click events emitted from the body element.

Also, we return function that calls removeListener to remove the body click listener when the component is unmounted.

And we pass in an empty array as the 2nd argument of useEffect to run the useEffect callback only when the component mounts.

Now when we click on the body element, we should see 'body clicked' logged in the console.

Conclusion

To add a click handler to the body element from within a React component, we call the addEventListener method on document.body in the useEffect hook callback to starting listening to clicks on the body element when the component loads.

Categories
React Answers

How to Use the marked Markdown Library in React?

Sometimes, we want to use the marked Markdown library in our React app.

In this article, we’ll look at how to use the marked Markdown library in our React app.

Use the marked Markdown Display Component in React

To use the marked Markdown display component in our React app, we just call, the marked function that comes with the marked library to convert the Markdown string into an HTML string.

Then we can render the HTML string with dangerouslySetInnerHTML .

For instance, we can write:

import React from "react";
import marked from "marked";
export default function App() {
  const getMarkdownText = () => {
    const rawMarkup = marked("This is _Markdown_.", { sanitize: true   });
    return { __html: rawMarkup };
  };

  return <div dangerouslySetInnerHTML={getMarkdownText()} />;
}

We create the getMarkdownText function to convert the “This is _Markdown_.” Markdown string into an HTML string with the marked function.

And we set sanitize to true to escape any special characters.

Then we set the dangerouslySetInnerHTML prop of the div to the HTML string returned by the getMarkdownText function.

Conclusion

To use the marked Markdown display component in our React app, we just call, the marked function that comes with the marked library to convert the Markdown string into an HTML string.

Then we can render the HTML string with dangerouslySetInnerHTML .