Categories
React Answers

How to Fix the “Uncaught TypeError: Cannot read property ‘push’ of undefined” Error When Developing Apps with React Router?

Sometimes, we may run into the "Uncaught TypeError: Cannot read property ‘push’ of undefined" error when developing apps with React Router.

In this article, we’ll look at how to fix the "Uncaught TypeError: Cannot read property ‘push’ of undefined" error when developing apps with React Router.

Fix the "Uncaught TypeError: Cannot read property ‘push’ of undefined" Error When Developing Apps with React Router

To fix the "Uncaught TypeError: Cannot read property ‘push’ of undefined" error when developing apps with React Router, we can get the history object from the useHistory hook.

For instance, we write:

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

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

const Bar = () => {
  const history = useHistory();
  return (
    <>
      <p>bar</p>
      <p onClick={() => history.push("/foo")}>foo</p>
    </>
  );
};

export default function App() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <NavLink to="/foo">foo</NavLink>
          </li>
          <li>
            <NavLink to="/bar">bar</NavLink>
          </li>
        </ul>

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

In the Bar component, we call useHistory to return the history object and assign it to history.

Then we call history.push in the function we set as the value of the onClick prop to go to the /foo page.

We can only call this inside route components and their children.

Otherwise, we’ll get the "Uncaught TypeError: Cannot read property ‘push’ of undefined" again.

Conclusion

To fix the "Uncaught TypeError: Cannot read property ‘push’ of undefined" error when developing apps with React Router, we can get the history object from the useHistory hook.

We can only call this inside route components and their children.

Categories
React Answers

How to Render Multiple React Components in a React Component?

Sometimes, we want to render multiple React components in a React component.

In this article, we’ll look at how to render multiple React components in a React component.

Render Multiple React Components in a React Component

To render multiple React components in a React component, we can render an array of components or we can render multiple components inside a fragment.

For instance, we write:

import React from "react";

const Foo = () => <div>foo</div>;

const Bar = () => <div>bar</div>;

export default function App() {
  return [<Foo />, <Bar />];
}

to render Foo and Bar together by putting them in an array.

To render them in a fragment, we write:

import React from "react";

const Foo = () => <div>foo</div>;

const Bar = () => <div>bar</div>;

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

or:

import React from "react";

const Foo = () => <div>foo</div>;

const Bar = () => <div>bar</div>;

export default function App() {
  return (
    <React.Fragment>
      <Foo />
      <Bar />
    </React.Fragment>
  );
}

Conclusion

To render multiple React components in a React component, we can render an array of components or we can render multiple components inside a fragment.

Categories
React Answers

How to Fix the “Objects are not valid as a React child (found: [object Promise])” Error When Developing React Apps?

Sometimes, we may run into the "Objects are not valid as a React child (found: [object Promise])" Error when developing React apps.

In this article, we’ll look at how to fix the "Objects are not valid as a React child (found: [object Promise])" Error when developing React apps.

Fix the "Objects are not valid as a React child (found: [object Promise])" Error When Developing React Apps

To fix the "Objects are not valid as a React child (found: [object Promise])" Error when developing React apps, we should make sure the states we’re rendering aren’t set to promises.

For instance, we write:

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

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

  const getAnswer = async () => {
    const res = await fetch("https://yesno.wtf/api");
    const json = await res.json();
    setVal(json.answer);
  };

  useEffect(() => {
    getAnswer();
  }, []);

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

We create the getAnswer function that gets data from an API with fetch.

Then we call res.json to convert the response data into a JSON object.

We put await before res.json to get the actual data object instead of a promise assigned to json.

Next, we call setVal to set val to the value of json.answer.

Then in the useEffect callback, we call getAnswer to get the data when the component mounts.

We pass in an empty array into useEffect to make sure the useEffect callback only runs when the component mounts.

And finally, we display the value of val in the div.

Conclusion

To fix the "Objects are not valid as a React child (found: [object Promise])" Error when developing React apps, we should make sure the states we’re rendering aren’t set to promises.

Categories
React Answers

How to Only Allow Numbers to be Entered in an Input in React?

Sometimes, we want to only allow numbers to be entered in an input in React.

In this article, we’ll look at how to only allow numbers to be entered in an input in React.

Only Allow Numbers to be Entered in an Input in React

To only allow numbers to be entered in an input in React, we can set the pattern attribute of the input to only allow digits to be inputted.

Then in the onChange handler, we only set the value of the input when the inputted value is valid.

For instance, we write:

import React, { useState } from "react";

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

  return (
    <div>
      <input
        type="text"
        pattern="[0-9]*"
        value={val}
        onChange={(e) =>
          setVal((v) => (e.target.validity.valid ? e.target.value : v))
        }
      />
    </div>
  );
}

We create the val state with the useState hook.

And we set that as the value of the value prop.

Then we add the pattern attribute and set it to a regex that only matches digits.

Finally, the onChange prop is set to a function that calls setVal with a function that takes the existing value of val, which is v.

And we check if the inputted value is valid with e.target.validity.valid .

If it is, we return the current inputted value, which is stored in e.target.value.

Otherwise, we return the current value of val which is v.

Conclusion

To only allow numbers to be entered in an input in React, we can set the pattern attribute of the input to only allow digits to be inputted.

Then in the onChange handler, we only set the value of the input when the inputted value is valid.

Categories
React Answers

How to Set the Port of the Dev Server in a Next.js Project?

Sometimes, we want to set the port of the dev server in a Next.js project.

In this article, we’ll look at how to set the port of the dev server in a Next.js project.

Set the Port of the Dev Server in a Next.js Project

To set the port of the dev server in a Next.js project, we can add the -p option to the dev command in package.json.

For instance, we write:

"scripts": { 
  "dev": "next -p 8080" 
},

to set the dev server to serve the project on port 8080.

We can also set the PORT environment variable before we run the dev script.

To do this, we type in:

PORT=8080 npx next dev

into the command to run the dev server on port 8080.

Conclusion

To set the port of the dev server in a Next.js project, we can add the -p option to the dev command in package.json.

We can also set the PORT environment variable before we run the dev script.