Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React and typescript dynamic grid resize

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading