Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nextjs does not render server side the default jsx of a boolean state

I have a simple nextjs page for the rendering of a Post. Everything run fine and nextjs render the complete page server side for a perfect SEO experience. However I wanted to add an edition mode using a boolean state:

const PostPage: NextPage = () => {
  const [editionMode, setEditionMode] = React.useState(false)

  return (
    <MainLayout>
     {editionMode ? <EditPostForm /> : <Post />}
    </MainLayout>
)

Sadly with this logic, nextjs doesn’t render server side the <Post />.

So I know I could just remove this condition, always render the <Post /> and put the <EditPostForm /> into a modal or simply add a new endpoint like /posts/:postId/edit, but I wanted to know if there was just a simpler way to handle this case with a simple boolean value so that nextjs still server side render the default one.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To generate SSR, you should use the getServerSideProps to provide the server side render props.

And your useState’s default value should get powered by the props.

const PostPage: NextPage = ({ data }) => {
  const [editionMode, setEditionMode] = React.useState(data.editMode)

  return (
    <MainLayout>
     {editionMode ? <EditPostForm /> : <Post />}
    </MainLayout>
);

// This gets called on every request
export async function getServerSideProps() {
  // Pass data to the page via props
  return { props: { data: { editMode: false } } };
}

I am curious about how your state becomes true to return the EditionMode component.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading