Skip to content

Instantly share code, notes, and snippets.

@karol-dabrowski
Last active July 16, 2022 20:07
Show Gist options
  • Save karol-dabrowski/1c1d3341f9dcf0d837d1afea6bea962a to your computer and use it in GitHub Desktop.
Save karol-dabrowski/1c1d3341f9dcf0d837d1afea6bea962a to your computer and use it in GitHub Desktop.
Getting parameters from URL address with URLSearchParams - React example
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