How do I change the size of an element using useState?

Viewed 29

I can maximize and minimize with the SIZE button. But if the user changes the size of the editor window manually, the code doesn't work. How can I fix it?

I think I have to change the useState to take a non-boolean value, but I don't know to what.

Here's the App.js code

import { useState } from 'react';
import Editor from './components/Editor';


function App() {

  const [content, setContent] = useState("")

  function handleChange(event) {
    setContent(event.target.value)
  }

  const [editorSize, setEditorSize] = useState(true)

  function toggleEditorSize() {
    setEditorSize(prevState => !prevState)
  }

  return (
    <div className="App">
  
      <Editor handleChange={handleChange} toggleEditorSize={toggleEditorSize} editorSize={editorSize}/>

    </div>
      
  );
}

export default App;

Here's the Editor.js code



export default function Editor(props) {

    return (
        <div>
            <div className="editor-header">
                <p className="editor-title">Editor</p>
                <button onClick={props.toggleEditorSize}>SIZE</button>
            </div>

            <textarea id="editor" className={props.editorSize ? "max": ""} onChange={props.handleChange} >
        
            </textarea>
            
            
        </div>
    )
}

Here's the Index.css code

  background-color: white;
  color: black;
  border: 2px solid black;
  position: relative;
  display: inline-block;
  overflow: scroll;
  border-top: none;
  min-width: 500px;
  min-height: 300px;
  max-width: 500px;
  max-height: 600px;
  height: 300px;
}

#editor.max, #preview.max {
  height: 600px;
}
1 Answers

Hear what's happening is you have render component to detect the changes happed. here everytime when you click button useEffect will run and check if editorSize is true or not. if it's then it will set "max" class name to state ( Size ) and then here

     <textarea id="editor" className={Size} onChange={props.handleChange} >
     </textarea>

className will be set. Well, this should work. if it doesn't works try adding important property to you css. like this,

#editor.max, #preview.max {
  height: 600px !important;
}

Here's the Editor.js code


export default function Editor(props) {

   const[Size, setSize] = useState("");

    useEffect(()=>{
        if(props.editorSize){
            setSize("max")
        } else {
            setSize("")
        }
    },[props.editorSize]);

    return (
        <div>
            <div className="editor-header">
                <p className="editor-title">Editor</p>
                <button onClick={props.toggleEditorSize}>SIZE</button>
            </div>

            <textarea id="editor" className={Size} onChange={props.handleChange} >
        
            </textarea>
            
            
        </div>
    )
}
Related