React url parameter without router. In this tutorial, i am going to show you how to get parameters value from in URL without using react-router in react js app.
In this example, i will create a simple home page with query string url and get parameter value from it using this.props.location.search in react js app.
Get Parameter Value From Query String in React JS
- Step 1 – Create React App
- Step 2 – Install Query String and Bootstrap 4 Package
- Step 3 – Create Home Component
- Step 4 – Add Component in App.js
Step 1 – Create React App
Start your terminal and run the following command on your terminal to create a new react app:
npx create-react-app my-react-app
To run the React app, execute the following command on your terminal:
npm start
Check out your React app on this URL: localhost:3000
Step 2 – Install Query String and Bootstrap 4 Package
Run the following commands to install query string and boostrap 4 library into your react app:
npm install bootstrap --save npm install query-string
Then, Add react router and bootstrap.min.css file in src/App.js
file:
import React from 'react'; import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; function App() { return ( <div> <h2>How to Get Parameter in URL in React js with Router</h2> </div> ); } export default App;
Step 3 – Create Home Component
Go to src directory of your react js app and create home component named Home.js. And add the following code into it:
import React from 'react' import queryString from 'query-string' class Home extends React.Component{ state = { site: 'unknown', subject: 'i dont know' } handleQueryString = () => { // Parsing the query string // Using parse method let queries = queryString.parse(this.props.location.search) console.log(queries) this.setState(queries) } render() { return ( <div style={{ margin: 200 }}> <p> WebSite: {this.state.site} </p> <p> Subject: {this.state.subject} </p> <button onClick={this.handleQueryString} className='btn btn-primary'> click me </button> </div> ); } } export default Home;
Let’s assume you have the following URL “http://localhost:3000/?site=laratutorials&subject=get-query-string” that can be displayed into react js application. So, when you clicking on the button, you will get query string parameter on your react js app page.
Step 4 – Import Component in App.js
Import Home.js file in src/App.js
file:
import React from 'react'; import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; iimport queryString from 'query-string' import Home from './Home' function App() { return ( <div className="App"> <Home /> </div> ); } export default App;
Conclusion
React url parameter without router. in this tutorial, you have learned how to get parameters value from in URL without using react-router in react js app.