Getting parameters from URL address with URLSearchParams - React example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
class App extends Component { | |
state = { | |
stringParam: '', | |
numberParam: 0 | |
} | |
componentDidMount() { | |
const queryParams = new URLSearchParams(window.location.search); | |
this.setState({ | |
stringParam: queryParams.get('string_param') ?? '', | |
numberParam: queryParams.get('number_param') ? parseInt(queryParams.get('number_param')) : 0 | |
}); | |
} | |
render() { | |
return ( | |
<div className="App"> | |
<div>String parameter: { this.state.stringParam.length > 0 ? this.state.stringParam : 'empty' }</div> | |
<div>Number parameter: { this.state.numberParam }</div> | |
</div> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment