Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional Components vs ES6 Classes in NextJS

All of the examples and tutorials of NextJs pages which presented in its docs and other references are with functional components.

So, What about classes? What happens to getInitialProps (or other features that mentioned in docs) when a functional component replaces with an ES6 class. Is that page still a NextJS page after replacing?

like image 493
Behnam Azimi Avatar asked Dec 01 '25 01:12

Behnam Azimi


1 Answers

You can use class components (as I usually do), just make sure that you add the static keyword to the getInitialProps method:

import React from 'react';
import PropTypes from 'prop-types';

export default class Gallery extends React.Component {
    static propTypes = {
        image: PropTypes.string
    };

    static getInitialProps() {
        return {...};
    }

    render() {
        return (
            <div>
                // render gallery
            </div>
        );
    }
}
like image 147
ForrestLyman Avatar answered Dec 04 '25 09:12

ForrestLyman