How to pass state in react router dom

hello every one.
i am trying to implement a MERN full stack sign up page and it has two divided component so that once the user has finished filling the first signup page they can click next and go to the second one.how i get stack is that i am trying to send the state value(all the user inputed values are stored in state) to the second signup component as props and in the second signup component it has its own state,so that i will be mixing the local state and props from the first signup component and send http request using axios to the server(backend) to save on the mongodb.but it seems impossible,since i am linking the two routers using react router dom v6.6.1 and using useLoaction is causing problem when importing it from react-router-dom.i created topic(discussion) on github on their page,but no response yet.it says or gives error:-

Attempted import error: 'useLoaction' is not exported from 'react-router-dom' (imported as 'useLoaction').
ERROR in ./src/components/signup2.jsx 10:19-30
export 'useLoaction' (imported as 'useLoaction') was not found in 'react-router-dom' (possible exports: AbortedDeferredError, Await, BrowserRouter, Form, HashRouter, Link, MemoryRouter, NavLink, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, ScrollRestoration, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_DataStaticRouterContext, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, UNSAFE_enhanceManualRouteObjects, UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, createSearchParams, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, renderMatches, resolvePath, unstable_HistoryRouter, useActionData, useAsyncError, useAsyncValue, useBeforeUnload, useFetcher, 
useFetchers, useFormAction, useHref, useInRouterContext, useLinkClickHandler, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes, useSearchParams, useSubmit)

ERROR in ./src/components/signup2.jsx 22:10-21
export 'useLoaction' (imported as 'useLoaction') was not found in 'react-router-dom' (possible exports: AbortedDeferredError, Await, BrowserRouter, Form, HashRouter, Link, MemoryRouter, NavLink, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, ScrollRestoration, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_DataStaticRouterContext, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, UNSAFE_enhanceManualRouteObjects, UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, createSearchParams, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, renderMatches, resolvePath, unstable_HistoryRouter, useActionData, useAsyncError, useAsyncValue, useBeforeUnload, useFetcher, 
useFetchers, useFormAction, useHref, useInRouterContext, useLinkClickHandler, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes, useSearchParams, useSubmit)

webpack compiled with 2 errors

i tried searching for this error but can not find any fixes also useLocation can not be used in class components,but i came up with the idea of nesting the second signup component in functional component to use that hook and send the values return to the class component(seen it from youtube not sure it work) but left with the above error.you know i thought it would be better sending the state to the2nd component and finally send the request once instead of sending the request separately to the same route and i think it is not allowed.any ideas to fix this issue appreciated.here is the code:-
App.jsx

import React from "react";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
import Login from "./components/login";
import SignUp from "./components/signup";
import SignUpFinal from "./components/signup2";

function App() {
  return (
    <Router>
      <div className="App">
        <nav className="navbar navbar-expand-lg navbar-light fixed-top">
          <div className="container">
            <Link className="navbar-brand" to={"/sign-in"}>
              positronX
            </Link>
            <div className="collapse navbar-collapse" id="navbarTogglerDemo02">
              <ul className="navbar-nav ml-auto">
                <li className="nav-item">
                  <Link className="nav-link" to={"/sign-in"}>
                    Login
                  </Link>
                </li>
                <li className="nav-item">
                  <Link className="nav-link" to={"/sign-up"}>
                    Sign up
                  </Link>
                </li>
              </ul>
            </div>
          </div>
        </nav>
        <div className="auth-wrapper">
          <div className="auth-inner">
            <Routes>
              <Route exact path="/" element={<Login />} />
              <Route path="/sign-in" element={<Login />} />
              <Route path="/sign-up" element={<SignUp />} />
              <Route path="/sign-up2" element={<SignUpFinal />} />
            </Routes>
          </div>
        </div>
      </div>
    </Router>
  );
}
export default App;

signup.jsx

import React, { Component } from "react";
import { Link } from "react-router-dom";

const deps = {
  ElectricalandComputerEngineering: [
    "None",
    "Computer Engineering",
    "Control Engineering",
    "Power Engineering",
    "Communication Engineering",
  ],
  ChemicalEngineering: ["None"],
  MinningEngineering: ["None", "e", "f", "g", "h"],
  CivilEngineering: ["None", "i", "j", "k", "l"],
  MechanicalEngineering: [
    "None",
    "Automotive Engineering",
    "Manufacture Engineering",
    "Design Engineering",
    "Thermal Engineering",
  ],
  SoftwareEngineering: ["None", "p", "q", "r", "s"],
  ElectromechanicalEngineering: ["None"],
  EnvironmentalEngineering: ["None"],
};

export default class SignUp extends Component {
  constructor(props) {
    super(props);

    this.state = {
      fullName: "",
      email: "",
      Id: "",
      department: "Electrical and Computer Engineering",
      stream: "None",
    };

    this.handleName = this.handleName.bind(this);
    this.handleEmail = this.handleEmail.bind(this);
    this.handleId = this.handleId.bind(this);
    this.handleDep = this.handleDep.bind(this);
    this.handleStr = this.handleStr.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleName(e) {
    this.setState({
      fullName: e.target.value,
    });
  }
  handleEmail(e) {
    this.setState({
      email: e.target.value,
    });
  }
  handleId(e) {
    this.setState({
      Id: e.target.value,
    });
  }
  handleDep(e) {
    this.setState({
      department: e.target.value,
    });
    const dep = this.state.department.split(" ").join("");
    const stream = deps[dep][0];
    this.setState({
      stream
    });
  }
  handleStr(e) {
    this.setState({
      stream: e.target.value,
    });
  }
  handleSubmit(e) {
    e.preventDefault();
  }

  render() {
    const dep = this.state.department.split(" ").join("");
    console.log(dep);
    const stream = deps[dep];

    console.log(stream);
    console.log(this.state.stream);

    return (
      <form onSubmit={this.handleSubmit}>
        <h3>Sign Up</h3>

        <div className="mb-3">
          <label htmlFor="name">Full name</label>
          <input
            type="text"
            id="name"
            value={this.state.fullName}
            onChange={this.handleName}
            className="form-control"
            placeholder="Grand Father name should be included"
            required
          />
        </div>

        <div className="mb-3">
          <label htmlFor="email">Email address</label>
          <input
            type="email"
            id="email"
            value={this.state.email}
            onChange={this.handleEmail}
            className="form-control"
            placeholder="Enter email"
            required
          />
        </div>

        <div className="mb-3">
          <label htmlFor="ide">ID</label>
          <input
            type="text"
            id="ide"
            value={this.state.Id}
            onChange={this.handleId}
            className="form-control"
            placeholder="ETS0155/10"
            required
          />
        </div>

        <div className="mb-3">
          <label htmlFor="dep">Department</label>
          {/* <input type="text" className="form-control" placeholder="Last name" /> */}
          <select
            id="dep"
            value={this.state.department}
            onChange={this.handleDep}
            required
          >
            <option>Electrical and Computer Engineering</option>
            <option>Chemical Engineering</option>
            <option>Minning Engineering</option>
            <option>Civil Engineering</option>
            <option>Mechanical Engineering</option>
            <option>Software Engineering</option>
            <option>Electromechanical Engineering</option>
            <option>Environmental Engineering</option>
          </select>
        </div>

        <div className="mb-3">
          <label htmlFor="str">Stream</label>
          {/* <input type="text" className="form-control" placeholder="Last name" /> */}
          <select
            id="str"
            value={this.state.stream}
            onChange={this.handleStr}
            required
          >
            {stream && stream.map((st) => <option key={st}>{st}</option>)}
          </select>
        </div>

        <div className="d-grid">
          <Link to={"/sign-up2"} state={this.state}>
            <button type="submit" className="btn btn-primary">
              Next
            </button>
          </Link>
        </div>

        <p className="forgot-password text-right">
          Already registered <a href="/sign-in">sign in?</a>
        </p>
      </form>
    );
  }
}

signup2.jsx

import React, { Component } from "react";
import { useLoaction } from "react-router-dom";

export function Stat(props) {
  const location = useLoaction();
  const state = location.state;
  console.log(state);
  return <SignUpFinal state={state} />;
}

export default class SignUpFinal extends Component {
  constructor(props) {
    super(props);

    this.state = {
      batch: 1,
      sex: "Male",
      age: 18,
      phoneNumber: "0984678119 or 0719377416",
      password: "",
    };

    this.handleBat = this.handleBat.bind(this);
    this.handleSex = this.handleSex.bind(this);
    this.handleAge = this.handleAge.bind(this);
    this.handlePhone = this.handlePhone.bind(this);
    this.handlePass = this.handlePass.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleBat(e) {
    this.setState({
      batch: e.target.value,
    });
  }
  handleSex(e) {
    this.setState({
      sex: e.target.value,
    });
  }
  handleAge(e) {
    this.setState({
      age: e.target.value,
    });
  }
  handlePhone(e) {
    this.setState({
      phoneNumber: e.target.value,
    });
  }
  handlePass(e) {
    this.setState({
      password: e.target.value,
    });
  }
  handleSubmit(e) {
    e.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <h3>Sign Up</h3>
        {console.log(this.props.obj)}
        <div className="mb-3">
          <label htmlFor="bat">Batch</label>
          <select
            id="bat"
            value={this.state.batch}
            onChange={this.handleBat}
            required
          >
            <option>1</option>
            <option>2</option>
            <option>3</option>
            <option>4</option>
            <option>5</option>
            <option>6</option>
          </select>
        </div>

        <div className="mb-3">
          <label htmlFor="sex">Sex</label>
          <select
            id="sex"
            value={this.state.sex}
            onChange={this.handleSex}
            required
          >
            <option>Male</option>
            <option>Female</option>
          </select>
        </div>

        <div className="mb-3">
          <label htmlFor="age">Age</label>
          <input
            type="number"
            id="age"
            min="18"
            max="70"
            value={this.state.age}
            onChange={this.handleAge}
            className="form-control"
            placeholder="Enter your Age"
            required
          />
        </div>

        <div className="mb-3">
          <label htmlFor="num">Phone Number</label>
          <input
            type="tel"
            id="num"
            pattern="[0]{1}[97]{1}[0-9]{8}"
            value={this.state.phoneNumber}
            onChange={this.handlePhone}
            className="form-control"
            placeholder="Enter your Phone Number"
            required
          />
        </div>

        <div className="mb-3">
          <label htmlFor="pass">Password</label>
          <input
            type="password"
            id="pass"
            value={this.state.password}
            onChange={this.handlePass}
            className="form-control"
            placeholder="Enter your password"
            required
          />
        </div>

        <div className="d-grid">
          <button type="submit" className="btn btn-primary">
            Submit
          </button>
        </div>

        <p className="forgot-password text-right">
          Already registered <a href="/sign-in">sign in?</a>
        </p>
      </form>
    );
  }
}

“location”, not “loacation”, the error is saying there is no export useLoacation

Also, this is hook, used with function components: why try to jerry-rig class components to make it work, why not just use function components as it’s designed for?

OMG,what a shame how i did not saw that,i think i may need a lens :face_with_monocle:

well i used class components because i need to have state to track the data and i think functional component does not have states?

About 6 years ago, yes, but hasn’t been the case since then, that’s why hooks exist, the class syntax is very rarely used since they appeared.

Also, if you are in an editor, locally, install a spell checker and it will catch most of the typos like this. I like Code Spell Checker on VS Code.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.