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.
>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.