简体   繁体   中英

How to show a loading spinner until component loads in React

My question is not as simple as the title. I'm trying to show a loading component for 1 second and then replace that component with the actual data.

Here is my code:

const TopNavigationAuth = () => (
<Container>
    <Menu.Item
        name="landing"
        content="Landing"
        as={Link}
        to={routes.LANDING}
    />
    <Menu.Item name="home" content="Home" as={Link} to={routes.HOME} />
    <Menu.Menu position="right">
        <Menu.Item
            name="account"
            content="Account"
            as={Link}
            to={routes.ACCOUNT}
        />
        <UserSection />
        <Menu.Item
            name="signout"
            content={
                <Button
                    content="Sign Out"
                    onClick={authFunctions.doSignOut}
                    primary
                />
            }
        />
    </Menu.Menu>
</Container>
);

So here I have the <UserSection /> component which essentially just holds the user's picture and name (for now). I would like to load that component after 1 or 2 seconds but until then I would like to show a spinner instead.

I'm using semantic ui react for my app and they have a handy spinner which looks like this:

const LoaderExampleInlineCentered = () => <Loader active inline='centered' />

Can I please have some guidance with this?

You can conditionally render one of the two components, Loader Or UserSection.

this.state.profileExist === true ? <UserSection /> : <Loader />

Then initialize profileExist as a False in componentDid mount, then use setTimeout to set it to true

componentDidMount() {
    this.setState({profileExist: false})
    setTimeout(() => { 
          this.setState({profileExist: true})
    }, 1000);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM