Skip to content

Instantly share code, notes, and snippets.

@monzou
Last active October 13, 2020 10:58
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save monzou/235655ee22db57fd1187d661e1312fbb to your computer and use it in GitHub Desktop.
Save monzou/235655ee22db57fd1187d661e1312fbb to your computer and use it in GitHub Desktop.
Next.js + TypeScript
import { Context } from 'next'
import Head from 'next/head'
import * as React from 'react'
import { compose, lifecycle, pure, wrapDisplayName } from 'recompose'
function withInitialProps<Props>(provider: (context: Context) => object) {
return (BaseComponent: React.ComponentType<Props>) => {
return class extends React.Component<Props> {
public static displayName = wrapDisplayName(BaseComponent, 'withInitialProps')
public static async getInitialProps(context: Context) {
if (BaseComponent.getInitialProps) {
return BaseComponent.getInitialProps(context)
}
return provider(context)
}
public render() {
return <BaseComponent {...this.props} />
}
}
}
}
interface IndexProps {
name: string
pathname?: string
}
const Index: React.SFC<IndexProps> = props => (
<div>
<Head>
<title>Hello, {props.name} !</title>
</Head>
Hello, {props.name} => {props.pathname}
<style jsx>{`
color: #666;
`}</style>
</div>
)
const enhance = compose<IndexProps, {}>(
withInitialProps(async (context: Context) => {
return {
pathname: context.pathname
}
}),
lifecycle({
componentDidMount() {
console.log('mounted')
}
}),
pure
)
export default enhance((props: IndexProps) => {
return <Index name="Next.js 5" {...props} />
})
import * as http from "http";
import * as React from "react";
declare module "next" {
export interface Context {
readonly pathname: string;
readonly query: string;
readonly asPath: string;
readonly req: http.IncomingMessage;
readonly res: http.ServerResponse;
readonly jsonPageRes: Response;
readonly err: any;
}
}
declare module "react" {
interface ComponentClass<P = {}> {
static getInitialProps?: (context: Context) => object;
}
interface StatelessComponent<P = {}> {
static getInitialProps?: (context: Context) => object;
}
}
import "react";
declare module "react" {
interface StyleHTMLAttributes<T> extends React.HTMLAttributes<T> {
jsx?: boolean;
global?: boolean;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment