Next.js Tutorial For Beginners

nextjs-youtube-demo

Global Layout and CSS

Nav

dynamic className base on the route

getStaticProps

export async function getStaticProps() {
  const response = await fetch("https://learnwebcode.github.io/json-example/posts.json")
  const data = await response.json()

  return {
    props: {
      posts: data.posts
    }
  }
}

Dynamic route

Change route

getStaticPaths

export async function getStaticPaths() {
  const response = await fetch("https://learnwebcode.github.io/json-example/posts.json")
  const data = await response.json()

  const thePaths = data.posts.map(pet => {
    // slug => base on file name [slug].js
    return { params: { slug: pet.slug } }
  })

  return {
    paths: thePaths,
    fallback: false
  }
}

Module CSS

ISR

export default function About(props) {
  return (
    <>
      <h2>About Us</h2>
      <p>Welcome to this amazing about page. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Porro dolore officiis atque voluptas, quas, repellendus cum, magnam a alias unde reiciendis voluptates aliquam maxime laborum? Quae omnis eius impedit et?</p>
      <p>I have {props.repoCount} public repos on GitHub.</p>
    </>
  )
}

export async function getStaticProps() {
  const response = await fetch("https://api.github.com/users/learnwebcode")
  const data = await response.json()

  return {
    props: {
      repoCount: data.public_repos
    },
    // ISR
    revalidate: 10
  }
}

getServerSideProps

export default function Home(props) {
  return (
    <div>
      <h2>Welcome to our homepage.</h2>
      <p>This is the best home page in the world. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Earum aspernatur illum architecto cumque recusandae fuga sequi necessitatibus deleniti repellat harum nobis, dolor veniam vero deserunt. Voluptatibus, ducimus deserunt. Recusandae, dolore.</p>
      <p>The weather: {props.forecast}</p>
    </div>
  )
}

export async function getServerSideProps() {
  const response = await fetch("https://api.weather.gov/gridpoints/MFL/109,49/forecast")
  const data = await response.json()

  return {
    props: {
      forecast: data.properties.periods[0].detailedForecast
    }
  }
}