Categories
React Answers

How to Update a React Context from Inside a Child Component?

To update a React Context from inside a child component, we can wrap the React Context provider around the child components.

Then we set the value prop of the context provider to the the state setter function that lets us update the context value.

Then we can use the useContext hook to access the context.

For instance, we write:

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

const Context = React.createContext();

const Foo = () => {
  const [, setVal] = useContext(Context);

  return (
    <div>
      <button onClick={() => setVal("foo")}>foo</button>
    </div>
  );
};

const Bar = () => {
  const [, setVal] = useContext(Context);

  return (
    <div>
      <button onClick={() => setVal("bar")}>bar</button>
    </div>
  );
};

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

  return (
    <Context.Provider value={[val, setVal]}>
      <Foo />
      <Bar />
      <p>{val}</p>
    </Context.Provider>
  );
}

to create the Context context with the React.createContext method.

Next, we create the Foo component which calls the useContext hook with Context to return the value of its value prop.

In both Foo and Bar, we call setVal to set the value of val`.

val and setVal are passed down from the array we set as the value of the value prop of Context.Provider.

Since Foo and Bar are inside Context.Provider we can access the context’s value prop value with useContext.

Therefore, when we click the buttons, we see the val value in App change.

Categories
React Answers

How to Fix the ‘React eslint error missing in props validation’ When Developing a React App?

Sometimes, we run into the ‘React eslint error missing in props validation’ when developing a React app.

In this article, we’ll look at how to fix the ‘React eslint error missing in props validation’ when developing a React app.

Fix the ‘React eslint error missing in props validation’ When Developing a React App?

To fix the ‘React eslint error missing in props validation’ when developing a React app, we can set the prop types of the props in the component causing the error.

For instance, we write:

import React from "react";
import PropTypes from "prop-types";

const Foo = ({ someProp, onClick }) => {
  return <div onClick={onClick}>foo {someProp}</div>;
};

Foo.propTypes = {
  someProp: PropTypes.number.isRequired,
  onClick: PropTypes.func.isRequired
};

export default function App() {
  const onClick = () => console.log("clicked");

  return <Foo someProp={2} onClick={onClick} />;
}

to import the prop-types package to let us add prop type validation to the Foo component.

We install it by running:

npm i prop-types

We set the Foo.propTypes property to an object that has the prop names as the keys and the corresponding prop types as the values.

So someProp is a number and it’s required.

And onClick is a function and it’s also required.

Then in App, we render the Foo component with the props passed in.

Now we won’t get any errors from ESLint.

Conclusion

To fix the ‘React eslint error missing in props validation’ when developing a React app, we can set the prop types of the props in the component causing the error.

Categories
React Answers

How to Get Query Parameters from a Hash Fragment with React Router v5?

Sometimes, we want to get query parameters from a hash fragment with React Router v5.

In this article, we’ll look at how to get query parameters from a hash fragment with React Router v5.

Get Query Parameters from a Hash Fragment with React Router v5

To get query parameters from a hash fragment with React Router v5, we can use the useLocation hook to return the location object and use the location.hash property to get the hash part of the URL.

For instance, we write:

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  useLocation
} from "react-router-dom";

const Foo = () => {
  const location = useLocation();
  const params = new URLSearchParams(location.hash);

  return <div>foo {JSON.stringify([...params.entries()])}</div>;
};

const Bar = () => {
  return <div>bar</div>;
};

export default function App() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/foo#/?a=1&b=2">foo</Link>
          </li>
          <li>
            <Link to="/bar">bar</Link>
          </li>
        </ul>

        <Switch>
          <Route path="/foo" children={<Foo />} />
          <Route path="/bar" children={<Bar />} />
        </Switch>
      </div>
    </Router>
  );
}

We have the Foo component that calls the useLocation and assign the returned object to the location variable.

Then we get the hash part of the URL with the location.hash property.

Next, we parse the hash part of the URL into an object with the URLSearchParams constructor.

And then we get the entries from the parsed query string with the entries method.

In App, we define some Routes that map URLs to the components we defined.

And we add Links with the to prop set to a URL with the hash part in it in the first link.

Then when we click the first link, we see the array with the parsed query string from the hash part of the URL.

We should see:

foo [["#/?a","1"],["b","2"]]

displayed when we click foo.

Conclusion

To get query parameters from a hash fragment with React Router v5, we can use the useLocation hook to return the location object and use the location.hash property to get the hash part of the URL.

Categories
React Answers

How to Fix the ‘”JSX not allowed in files with extension ‘ .js'” Error with eslint-config-airbnb When Developing a React App?

Sometimes, we want to fix the ‘"JSX not allowed in files with extension ‘ .js’" Error with eslint-config-airbnb when developing a React app.

In this article, we’ll look at how to fix the ‘"JSX not allowed in files with extension ‘ .js’" Error with eslint-config-airbnb when developing a React app.

Fix the ‘"JSX not allowed in files with extension ‘ .js’" Error with eslint-config-airbnb When Developing a React App

To fix the ‘"JSX not allowed in files with extension ‘ .js’" Error with eslint-config-airbnb when developing a React app, we can add the "react/jsx-filename-extension" to allow files with the .js extension to include JSX code in our .eslintrc file.

To do this, we write:

"rules": {
  "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],
}

to allow JSX code to be added to files with the .js and .jsx extensions.

Conclusion

To fix the ‘"JSX not allowed in files with extension ‘ .js’" Error with eslint-config-airbnb when developing a React app, we can add the "react/jsx-filename-extension" to allow files with the .js extension to include JSX code in our .eslintrc file.

Categories
React Answers

How to Fix the ‘Await is a reserved word error inside async function’ Error When Developing a React App?

Sometimes, we may run into the ‘Await is a reserved word error inside async function’ error when developing a React app.

In this article, we’ll look at how to fix the ‘Await is a reserved word error inside async function’ error when developing a React app.

Fix the ‘Await is a reserved word error inside async function’ Error When Developing a React App

To fix the ‘Await is a reserved word error inside async function’ error when developing a React app, we should make sure we make any function that uses the await keyword an async function.

For instance, instead of writing:

export const sendVerificationEmail = async () =>
  (dispatch) => {
    try {
      dispatch({ type: EMAIL_FETCHING, payload: true });
      await Auth.sendEmailVerification();
      dispatch({ type: EMAIL_FETCHING, payload: false }))
    } catch (error) {
      dispatch({ type: EMAIL_FETCHING, payload: false });
      throw new Error(error);
    }
  };

We write:

export const sendVerificationEmail = async () =>
  async (dispatch) => {
    try {
      dispatch({ type: EMAIL_FETCHING, payload: true });
      await Auth.sendEmailVerification();
      dispatch({ type: EMAIL_FETCHING, payload: false }))
    } catch (error) {
      dispatch({ type: EMAIL_FETCHING, payload: false });
      throw new Error(error);
    }
  };

We add the async keyword to the function we returned in the sendVerificationEmail function.

Conclusion

To fix the ‘Await is a reserved word error inside async function’ error when developing a React app, we should make sure we make any function that uses the await keyword an async function.