【Next.js】基本的な使い方と特徴

– Next.jsはjsのみ。HTMLファイルは使わずに開発を行う
– Netx.jsでは、Reactとは異なり、複数ページ開発できる

{
    "scripts": {
        "dev": "next",
        "build": "next build",
        "start": "next start",
        "export": "next export"
    }
}

$ npm install –save next react react-dom

pages/index.js

export default () => <div>
    <h1>Next.js</h1>
    <div>Welcome to next.js!</div>
</div>

$ npm run dev

next.config.js

module.exports = {
    exportPathMap: function() {
        return {
            '/': {page: '/'}
        }
    }
}

$ npm run build

const h1 = {
    fontSize:'72pt',
    fontWeight:'bold',
    textAlign:'right',
    letterSpacing:'-8px',
    color:'#f0f0f0',
    margin:'-40px 0px'
}

const p = {
    margin:'0px',
    color:'#666',
    fontSize:'16pt'
}


export default () => <div>
    <h1 style={h1}>Next.js</h1>
    <p style={p}>Welcome to next.js!</p>
</div>

### 複数ページの開発
index.js

import Link from 'next/link';

const h1 = {
    fontSize:'72pt',
    fontWeight:'bold',
    textAlign:'right',
    letterSpacing:'-8px',
    color:'#f0f0f0',
    margin:'-40px 0px'
}

const p = {
    margin:'0px',
    color:'#666',
    fontSize:'16pt'
}


export default () => <div>
    <h1 style={h1}>Next.js</h1>
    <p style={p}>Welcome to next.js!</p>
    <hr />
    <div>
        <Link href="/other">
            Go to Other page &gt;&gt;
        </Link>
    </div>
</div>

other.js

import Link from 'next/link';

const h1 = {
    fontSize:'72pt',
    fontWeight:'bold',
    textAlign:'right',
    letterSpacing:'-8px',
    color:'#f0f0f0',
    margin:'-40px 0px'
}

const p = {
    margin:'0px',
    color:'#666',
    fontSize:'16pt'
}


export default () => <div>
    <h1 style={h1}>Next.js</h1>
    <p style={p}>This is Other page.</p>
    <hr />
    <div>
        <Link href="/">
            &lt;&lt;Back to Index page
        </Link>
    </div>
</div>

### Component
Counter.js

import React, { Component } from 'react';

export default class Counter extends Component {
    msgStyle = {
        fontSize:"16pt",
        backgroundColor:"#eef",
        padding:"5px"
    }

    constructor(props) {
        super(props);
        this.state = {
            counter:0,
            msg: 'counter: 0',
        };
        this.doAction = this.doAction.bind(this);
    }

    doAction() {
        this.setState((state) => {
            const num = state.counter + 1;
            return ({
                counter: num,
                msg: "counter: " + num
            });
        });
    }

    render() {
        return <p onClick={this.doAction}
            style={this.msgStyle}>
            {this.state.msg}
        </p>;
    }
}
import Counter from '../components/Counter';
import style from '../static/Style';

export default () => <div>
    {style}
    <h1>Next.js</h1>
    <p>Welcome to next.js!</p>
    <hr />
    <Counter />
</div>

Reactをより使いやすくした って感じやね