Skip to content

Instantly share code, notes, and snippets.

@webuxmotion
Created November 13, 2020 09:09
Show Gist options
  • Save webuxmotion/e159afc6b1d1c4ba08a065318798f869 to your computer and use it in GitHub Desktop.
Save webuxmotion/e159afc6b1d1c4ba08a065318798f869 to your computer and use it in GitHub Desktop.
Extract parameters from url in nextjs
// Variant 1.
import { useRouter } from 'next/router';
const MyComponent = () => {
const router = useRouter();
const { query: { id } } = router;
return (
<h1>ID: {id}</h1>
)
}
export default MyComponent;
// Variant 2.
const MyComponent = ({ query: { id }}) => {
return (
<h1>ID: {id}</h1>
)
}
MyComponent.getInitialProps = ({ query }) => ({ query })
export default MyComponent;
// Variant 3.
import React from 'react';
class MyComponent extends React.Component {
static getInitialProps({ query }) {
return { query }
}
render() {
const { query: { id }} = this.props;
return (
<h1>ID: {id}</h1>
)
}
}
export default MyComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment