Skip to content

Instantly share code, notes, and snippets.

@monzou monzou/index.ts
Last active Aug 9, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.