article

Sunday, October 31, 2021

ReactJS Get String Parameter - React Router Dom

ReactJS Get String Parameter - React Router Dom

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ReactJS </title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import {
  BrowserRouter as Router, Switch, Route, useLocation,
} from "react-router-dom"; //$npm install -save react-router-dom

const App = () => {
  return (
    <Router>
      <Switch>
        <Route path="/">
          <Home/>
        </Route>
      </Switch>
    </Router>
  );
};

const Home = (props) => {
  const location = useLocation(); //useLocation hook to get the location object that represents the current URL
  const search = location.search;
  console.log(search);

  const params = new URLSearchParams(search);
  console.log(params.get("s"));

  return (
    <div
      style={{
        display: "flex",
        alignItems: 'center',
        flexDirection: 'column',
        marginTop: 100,
      }}
    >
      <h3>ReactJS Get String Parameter - React Router Dom </h3>
      <h3>S: {params.get("s")}</h3>
      <h3>Page: {params.get("page")}</h3>
      <h3>Limit: {params.get("limit")}</h3>
      <h3>Order: {params.get("order")}</h3>
    </div>
  );
};

export default App;

Related Post