Material-UI es una biblioteca de interfaz de usuario que proporciona componentes robustos y personalizables predefinidos para React para facilitar el desarrollo web. El diseño de MUI se basa en la parte superior de Material Design de Google.
En este artículo, discutiremos la API StepButton de React MUI. Los Steppers se utilizan para transmitir números en algunos pasos. StepButton se usa para crear botones para cambiar pasos en el Stepper. La API proporciona muchas funcionalidades y vamos a aprender a implementarlas.
Importar API de botón de paso
import StepButton from '@mui/material/StepButton'; // or import { StepButton } from '@mui/material';
Lista de accesorios: aquí está la lista de accesorios utilizados con este componente. Podemos acceder a ellos y modificarlos según nuestras necesidades.
- children : Es un componente similar a la fila de la tabla.
- clases : esto anula los estilos existentes o agrega nuevos estilos al componente.
- sx : El accesorio del sistema permite definir anulaciones del sistema, así como estilos CSS adicionales.
- Optional : Es el Node opcional a mostrar.
- icon : Es la etiqueta que se muestra en el icono de paso.
Sintaxis: Cree un StepButton dentro de Step de la siguiente manera:
<Step> <StepButton onClick={handleStep(index)}> Next </StepButton> </Step>
Instalar y crear la aplicación React y agregar las dependencias de MUI.
Paso 1: Cree un proyecto de reacción usando el siguiente comando.
npx create-react-app gfg_tutorial
Paso 2: Entrar en el directorio del proyecto
cd gfg_tutorial
Paso 3: instale las dependencias de MUI de la siguiente manera:
npm install @mui/material @emotion/react @emotion/styled @mui/lab @mui/icons-material
Paso 4 : Ejecute el proyecto de la siguiente manera:
npm start
Ejemplo 1: En el siguiente ejemplo, tenemos StepButton en el Stepper.
App.js
import "./App.css"; import * as React from "react"; import Box from "@mui/material/Box"; import Stepper from "@mui/material/Stepper"; import Step from "@mui/material/Step"; import StepButton from "@mui/material/StepButton"; import Button from "@mui/material/Button"; import Typography from "@mui/material/Typography"; const steps = ["Basic Programming", "Data Structures", "Algorithms"]; function App() { const [activeStep, setActiveStep] = React.useState(0); const [completed, setCompleted] = React.useState({}); const totalSteps = () => { return steps.length; }; const completedSteps = () => { return Object.keys(completed).length; }; const isLastStep = () => { return activeStep === totalSteps() - 1; }; const allStepsCompleted = () => { return completedSteps() === totalSteps(); }; const handleNext = () => { const newActiveStep = isLastStep() && !allStepsCompleted() ? // It's the last step, but not all // steps have been completed, // find the first step that has been completed steps.findIndex((step, i) => !(i in completed)) : activeStep + 1; setActiveStep(newActiveStep); }; const handleBack = () => { setActiveStep((prevActiveStep) => prevActiveStep - 1); }; const handleStep = (step) => () => { setActiveStep(step); }; const handleComplete = () => { const newCompleted = completed; newCompleted[activeStep] = true; setCompleted(newCompleted); handleNext(); }; const handleReset = () => { setActiveStep(0); setCompleted({}); }; return ( <div className="App"> <div className="head" style={{ width: "fit-content", margin: "auto", }} > <h1 style={{ color: "green", }} > GeeksforGeeks </h1> <strong>React MUI StepButton API</strong> </div> <br /> <Box sx={{ width: "80%", margin: "auto" }}> <Stepper nonLinear activeStep={activeStep}> {steps.map((label, index) => ( <Step key={label} completed={completed[index]}> <StepButton color="inherit" onClick={handleStep(index)}> {label} </StepButton> </Step> ))} </Stepper> <div> {allStepsCompleted() ? ( <React.Fragment> <Typography sx={{ mt: 2, mb: 1 }}> All steps completed - you're finished </Typography> <Box sx={{ display: "flex", flexDirection: "row", pt: 2 }}> <Box sx={{ flex: "1 1 auto" }} /> <Button onClick={handleReset}>Reset</Button> </Box> </React.Fragment> ) : ( <React.Fragment> <Typography sx={{ mt: 2, mb: 1 }}> Step {activeStep + 1} </Typography> <Box sx={{ display: "flex", flexDirection: "row", pt: 2 }}> <Button color="inherit" disabled={activeStep === 0} onClick={handleBack} sx={{ mr: 1 }} > Back </Button> <Box sx={{ flex: "1 1 auto" }} /> <Button onClick={handleNext} sx={{ mr: 1 }}> Next </Button> {activeStep !== steps.length && (completed[activeStep] ? ( <Typography variant="caption" sx={{ display: "inline-block" }} > Step {activeStep + 1} already completed </Typography> ) : ( <Button onClick={handleComplete}> {completedSteps() === totalSteps() - 1 ? "Finish" : "Complete Step"} </Button> ))} </Box> </React.Fragment> )} </div> </Box> </div> ); } export default App;
Producción:
Ejemplo 2: En el siguiente ejemplo, hemos agregado un elemento opcional al StepButton.
App.js
import "./App.css"; import * as React from "react"; import Box from "@mui/material/Box"; import Stepper from "@mui/material/Stepper"; import Step from "@mui/material/Step"; import StepButton from "@mui/material/StepButton"; import Button from "@mui/material/Button"; import Typography from "@mui/material/Typography"; const steps = ["Basic Programming", "Data Structures", "Algorithms"]; const optIndex = 1; function App() { const [activeStep, setActiveStep] = React.useState(0); const [completed, setCompleted] = React.useState({}); const totalSteps = () => { return steps.length; }; const completedSteps = () => { return Object.keys(completed).length; }; const isLastStep = () => { return activeStep === totalSteps() - 1; }; const allStepsCompleted = () => { return completedSteps() === totalSteps(); }; const handleNext = () => { const newActiveStep = isLastStep() && !allStepsCompleted() ? // It's the last step, but not all // steps have been completed, // find the first step that has been completed steps.findIndex((step, i) => !(i in completed)) : activeStep + 1; setActiveStep(newActiveStep); }; const handleBack = () => { setActiveStep((prevActiveStep) => prevActiveStep - 1); }; const handleStep = (step) => () => { setActiveStep(step); }; const handleComplete = () => { const newCompleted = completed; newCompleted[activeStep] = true; setCompleted(newCompleted); handleNext(); }; const handleReset = () => { setActiveStep(0); setCompleted({}); }; return ( <div className="App"> <div className="head" style={{ width: "fit-content", margin: "auto", }} > <h1 style={{ color: "green", }} > GeeksforGeeks </h1> <strong>React MUI StepButton API</strong> </div> <br /> <Box sx={{ width: "80%", margin: "auto" }}> <Stepper nonLinear activeStep={activeStep}> {steps.map((label, index) => ( <Step key={label} completed={completed[index]}> <StepButton color="inherit" onClick={handleStep(index)} optional={ optIndex == index ? ( <Typography> This is optional</Typography> ) : null } > {label} </StepButton> </Step> ))} </Stepper> <div> {allStepsCompleted() ? ( <React.Fragment> <Typography sx={{ mt: 2, mb: 1 }}> All steps completed - you're finished </Typography> <Box sx={{ display: "flex", flexDirection: "row", pt: 2 }}> <Box sx={{ flex: "1 1 auto" }} /> <Button onClick={handleReset}> Reset</Button> </Box> </React.Fragment> ) : ( <React.Fragment> <Typography sx={{ mt: 2, mb: 1 }}> Step {activeStep + 1} </Typography> <Box sx={{ display: "flex", flexDirection: "row", pt: 2 }}> <Button color="inherit" disabled={activeStep === 0} onClick={handleBack} sx={{ mr: 1 }} > Back </Button> <Box sx={{ flex: "1 1 auto" }} /> <Button onClick={handleNext} sx={{ mr: 1 }}> Next </Button> {activeStep !== steps.length && (completed[activeStep] ? ( <Typography variant="caption" sx={{ display: "inline-block" }} > Step {activeStep + 1} already completed </Typography> ) : ( <Button onClick={handleComplete}> {completedSteps() === totalSteps() - 1 ? "Finish" : "Complete Step"} </Button> ))} </Box> </React.Fragment> )} </div> </Box> </div> ); } export default App;
Producción:
Referencia: https://mui.com/material-ui/api/step-button/
Publicación traducida automáticamente
Artículo escrito por manavsarkar07 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA