DAWM

Regresar

React - Hooks: useState II

react banner

El Hook de useState ofrece una variable de estado para mantener los datos entre renderizados y una función que coloca el estado para actualizar la variable y provocar que React renderice el componente nuevamente.

Fuente: Managing component state with the useState Hook

App.tsx: Hook - useState


import * as React from 'react';

...
...

function App() {

  {/* Hooks: useState */}
  const [plan, setPlan] = React.useState(new Array<String>());
  const [result, setResult] = React.useState(new Array<String>());

  ...

}

App.tsx: Callbacks


...

function App() {

  {/* Hooks: useState */}
  ...

  {/* Callbacks */}
  const getPlan = (msgPlan: Array<String>) => {
    setPlan(msgPlan);
  };

  const getResult = (msgResult: Array<String>) => {
    setResult(msgResult);
  };

...

}
...
function App() {

	...
		<Grid xs={12} sm={12} md={12} lg={12} >
			<Calculator setPlan={getPlan} setResult={getResult}/>
		</Grid>
	...
}

Calculator.tsx: Callbacks como Props


...
export default function Calculator( {setPlan, setResult} ) {
...
}
...
export default function Calculator( {setPlan, setResult} ) {

  ...

  {/* Manejadores de eventos */}

  const handleChangeSelect = (event: SelectChangeEvent) => {
    let newMenuId = parseInt(event.target.value)
    setPlanId(newMenuId)

    /* Utiliza el nuevo índice para seleccionar un objeto en el arreglo */
    let newMenuItem = (newMenuId != -1)?menuItems[newMenuId]:null;

    /* Envía como parámetro un arreglo de cadenas de caracteres (atributos del objeto)  */
    setPlan([
      newMenuItem?.title, 
      newMenuItem?.subtitle, 
      newMenuItem?.description 
    ]);

  };

  const handleChangeRadio = (event: React.ChangeEvent<HTMLInputElement>) => {
    let newChangeId = parseInt((event.target as HTMLInputElement).value)
    setTimeId(newChangeId)
    
    /* Utiliza el nuevo índice para seleccionar un objeto en el arreglo */
    let newChageItem = (newChangeId != -1)?radioItems[newChangeId]:null;

    let month = (newChageItem?.title as String).substring(0,2)
    let subtotal = (parseInt(month)* 20).toString()
    let total = "$"+subtotal
    
    /* Envía como parámetro un arreglo de cadenas de caracteres (atributos del objeto) */
    setResult( [ newChageItem?.title, newChageItem?.description, total ])

  };

}

App.tsx: Variable de estado como Props


...
  return (
    
    <Grid container spacing={5}>

      {/* Calculator */}
      <Grid xs={12} sm={12} md={12} lg={12}>
        <Calculator setPlan={getPlan} setResult={getResult} />
      </Grid>

      {/* Plan */}
      <Grid xs={12} sm={6} md={6} lg={6}>
        <Plan title={plan[0]} subtitle={plan[1]} description={plan[2]} />
      </Grid>

      {/* Result */}
      <Grid xs={12} sm={6} md={6} lg={6}>
        <Result title={result[2]} subtitle={result[0]} description={plan[0] + " " + plan[1]}/>
      </Grid>

    </Grid>
  )
...

react_componentes_useState2-1

App.tsx: Renderización condicionada


...
  return (
    
    <Grid container spacing={5}>

      {/* Calculator */}
      <Grid xs={12} sm={12} md={12} lg={12}>
        <Calculator setPlan={getPlan} setResult={getResult} />
      </Grid>

      {/* Plan */}
      <Grid xs={12} sm={6} md={6} lg={6}>
        {
          plan.length>0?
            <Plan title={plan[0]} subtitle={plan[1]} description={plan[2]} />
          :
            <></>
        }
      </Grid>

      {/* Result */}
      <Grid xs={12} sm={6} md={6} lg={6}>
        {
          plan.length>0 && result.length>0?
            <Result title={result[2]} subtitle={result[0]} description={plan[0] + " " + plan[1]}/>
          :
            <></>
        }
      </Grid>

    </Grid>
  )
...

react_componentes_useState2-2

Resultado Final


react_componentes_useState2-3

Referencias