How to set the "save" button to summit and not "new"

Viewed 63

Sorry, this is my first post and I'm new to React. I have this code below and I use steps for the buttons, however I would like the save button to be the submit type and only it, thanks for your help now.

<React.Fragment>
              <React.Fragment>
              {activeStep === steps.length ? (
              <React.Fragment>
                <Typography variant="h5" gutterBottom>
                  Saved
                </Typography>
              </React.Fragment>
            ) : (
              <React.Fragment>
                
                <Box sx={{ display: 'flex', justifyContent: 'flex-end', mb: 4}}>
                  {activeStep !== 0 && (
                    <Button onClick={handleBack} sx={{ mt: 3, ml: 1 }}>
                      Back
                    </Button>
                  )}

                  <Button
                    variant="contained"
                    onClick={handleNext}
                    sx={{ mt: 3, ml: 1 }}
                  >
                    {activeStep === steps.length - 1 ? 'Save' : 'New'}
                  </Button>
                </Box>
                {getStepContent(activeStep)}
              </React.Fragment>
            )}
              </React.Fragment>
</React.Fragment>

and these are the steps functions

function CheckoutContent() {
  const [activeStep, setActiveStep] = React.useState(0);

  const handleNext = () => {
    setActiveStep(activeStep + 1);
  };

  const handleBack = () => {
    setActiveStep(activeStep - 1);
  };

i'm using material-ui for this.

2 Answers

If I understand your question, this is what you can do:

const savable = activeStep === steps.length;

<Button
type={savable ? "submit" : undefined}
variant="contained"
onClick={savable ? undefined : handleNext}
sx={{ mt: 3, ml: 1 }}
>
{savable ? "Save" : "New"}
</Button>

You can do a conditional rendering: Check the updated codesandbox

{activeStep === STEPS.length - 1 ? (
         <Button variant="contained"
                 type="submit"
                 sx={{ mt: 3, ml: 1 }}
        > Save </Button>
        ) : (
          <Button variant="contained"
                   onClick={handleNext}
                  sx={{ mt: 3, ml: 1 }}
          > New </Button>
        )}
Related