Why does passing a js statement to onclick in a button will be active immediately?

Viewed 39

EntryPageContent.js:

import Grid from '@material-ui/core/Grid';
import { Box, Button } from '@material-ui/core';
import { BrowserRouter as Router, Switch, Route, useHistory } from 'react-router-dom';

function EntryPageContent (){
    let history = useHistory();

    const changeURL =() =>{
        history.push('/login');
    }

    return (
        <Box className='h-screen w-screen bg-blue-200 overflow-x-hidden overflow-y-scroll'>
            <Box className='h-1/4 flex items-center justify-center'>READY YET APPLICATION ENTRY POINT</Box>
            <Box className=' h-3/4 w-full flex items-center justify-center'>
                <Grid container spacing={1} align='center'>
                    <Grid item xs={12} className='space-x-10 md:space-x-60'>
                        <Button variant="contained" color="primary" onClick={changeURL}>
                            Pharmacist
                        </Button>
                        <Button variant="contained" color="primary">
                            Pick Up
                        </Button>
                    </Grid>
                </Grid>
            </Box>
        </Box>
      );
}
 
export default EntryPageContent;

This is the correct version, where I pass the function changeURL to the onClick property of the button, but what I wonder is why does it always go to http://localhost:3000/login if I pass history.push('/login') directly to onClick instead of the function changeURL?

1 Answers

Because when you use onclick={expr}, expr gets evaluated to know what value to pass to onclick. Therefore if you do onclick={history.push('/login')}, you're directly evaluating history.push('/login').

Instead, you can use an arrow function like onclick={() => history.push('/login')}.

Related