Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use getStaticProps in component

I started a project with next js and typescript. I have a main component that I call it in the index.js page I use the getStaticProps function in the main component getStaticProps returns a prop object and when I log this prop in my main component I received undefined in my console. I want to know using the getStaticProps in the component is wrong and I have just to use that function in pages or not. I am a newbie in next js and I would be very grateful if anyone could help me.

this is my main component

import React from 'react';
import {IMain} from "../../../../interfaces/components/IMenu/IMain";

const Main:React.FC<IMain> = (props) => {
    console.log(props);
    return (
        <div>
        </div>
    );
};


export async function getServerSideProps() {
    return {
        props: {
            data: 'gg'
        }
    };
}

export default Main;

and this is my index.js page

import Text from "./../components/ui/Text/Text";
import Button from "../components/ui/Button/Button";
import Main from "../components/Menu/Desktop/Main/Main";

const Home = () => {
  return <Main/>;
};




export default Home;
like image 352
Ali Ehyaie Avatar asked Jun 27 '21 08:06

Ali Ehyaie


People also ask

Can I use getStaticProps in a component?

getStaticProps can only be exported from a page. You can't export it from non-page files.It will not work if you add getStaticProps as a property of the page component.

Can I use getServerSideProps in a component?

Bug Solution. You cannot use getServerSideProps in non-page components. getServerSideProps can only be exported from a page. You can't export it from non-page files.

When should you use getStaticProps?

You should use getStaticProps if: The data required to render the page is available at build time ahead of a user's request. The data comes from a headless CMS. The page must be pre-rendered (for SEO) and be very fast — getStaticProps generates HTML and JSON files, both of which can be cached by a CDN for performance.

How do I redirect from getStaticProps?

You can achieve this by just switching the function getStaticProps to getServerSideProps . The entire function will execute on the server and your redirection will happen. e.g.


1 Answers

getStaticProps can only be exported from a page. You can’t export it from non-page files.It will not work if you add getStaticProps as a property of the page component.

https://nextjs.org/docs/basic-features/data-fetching#only-allowed-in-a-page

like image 115
Anish Antony Avatar answered Sep 21 '22 22:09

Anish Antony