Tuesday

Get parameters from url as query params in react with typescript

 Call your react as >> localhost:3000?firstParam=123&secondParam=123&thirdParam=false

IQueryParams.tsx >>
type IQueryParams = {
  firstParam?: string;
  secondParam?: string;
  thirdParam?: boolean;
};

app.tsx>>
import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import Body from './router';

interface IProp {
}

class App extends React.PureComponent<IProp> {
  constructor(props: IProp) {
    super(props);
    this.setQueryParams = this.setQueryParams.bind(this);
  }

  componentDidMount() {
    this.setQueryParams();
  }

  setQueryParams() {
    const search = window.location.search;
    const params = new URLSearchParams(search);

    const params = {
      firstParam: params.get('firstParam'),
      secondParam: params.get('secondParam'),
      thirdParam: params.get('thirdParam'),
    };

    console.log(params);
  }

  render() {
    return (
      <Router>
        <div className="app">
          <Body />
        </div>
      </Router>
    );
  }
}

export default App;