Next.js: How use next hybrid AMP in class components

Created on 8 Feb 2020  路  2Comments  路  Source: vercel/next.js

how to use next/AMP
Hybrid AMP returns Invalid react hook should not use in class components.

Most helpful comment

Hi, you can not use a hook in a class component as this is a React limitation so you can create a function component to leverage inside of your class component.

const AmpMode = ({ children, ampOnly }) => {
    const isAmp = useAmp()
    if (ampOnly) {
      return isAmp ? children : null
    } 
    return isAmp ? null : children
}

class MyComp extends React.Component {
  render() {
    return (
      <>
        <AmpMode ampOnly>I'm only shown in AMP mode</AmpMode>
        <AmpMode>I'm only shown in non-AMP mode</AmpMode>
      </>
    )
  }
}

All 2 comments

Hi, you can not use a hook in a class component as this is a React limitation so you can create a function component to leverage inside of your class component.

const AmpMode = ({ children, ampOnly }) => {
    const isAmp = useAmp()
    if (ampOnly) {
      return isAmp ? children : null
    } 
    return isAmp ? null : children
}

class MyComp extends React.Component {
  render() {
    return (
      <>
        <AmpMode ampOnly>I'm only shown in AMP mode</AmpMode>
        <AmpMode>I'm only shown in non-AMP mode</AmpMode>
      </>
    )
  }
}

Thanks @ijjk. It helps me鈽猴笍

Was this page helpful?
0 / 5 - 0 ratings

Related issues

havefive picture havefive  路  3Comments

jesselee34 picture jesselee34  路  3Comments

kenji4569 picture kenji4569  路  3Comments

YarivGilad picture YarivGilad  路  3Comments

pie6k picture pie6k  路  3Comments