Home > Back-end >  React and typescript dynamic grid resize
React and typescript dynamic grid resize

Time:12-25

I'm trying to make dynamic grid resize by change lgEditorSize value using onClick action for react and typescript code.

Declare initial lgEditorSize value

const x: any = {};
x.lgEditorSize=6;

Change lgEditorSize value

<Box display='flex' justifyContent='right'>
      <span>Show or hide the sidebar using</span>
      <Button onClick={() => {x.lgEditorSize=12;}}> <ArrowBackIosIcon/> </Button>
      <Button onClick={() => {x.lgEditorSize=6;}}> <ArrowForwardIosIcon/> </Button>  
      <span>Button</span> 
</Box>


<GridContainer>
            <Grid item lg={x.lgEditorSize}>
                Contents
            </Grid>
<GridContainer>      

The value is changed but grid not resized,Any thoughts to resize Grid using Button action.

CodePudding user response:

You are changing the variable, but the Component isn't re-rendering because it doesn't know it needs to. To achieve re-renders, you need to use state, because React is smart enough to know that when a state changes, all the components using that state should re-render.

You should place the lgEditorSize into a state and use the state variable. It would look something like this.

const [lgEditorSize, setLgEditorSize] = useState<GridSize>(6); 

<Box display='flex' justifyContent='right'>
      <span>Show or hide the sidebar using</span>
      <Button onClick={() => setLgEditorSize(12)}> <ArrowBackIosIcon/> </Button>
      <Button onClick={() => setLgEditorSize(6)}> <ArrowForwardIosIcon/> </Button>  
      <span>Button</span> 
</Box>


<GridContainer>
            <Grid item lg={lgEditorSize}>
                Contents
            </Grid>
<GridContainer>  

You can read more about state and the React component lifecycle here: https://reactjs.org/docs/state-and-lifecycle.html

  • Related