Last active
July 16, 2022 20:07
-
-
Save karol-dabrowski/1c1d3341f9dcf0d837d1afea6bea962a to your computer and use it in GitHub Desktop.
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