I have some categories in my application. For each category, I'd like to add some images. So I added one Modal in reactstrap to show a modal window to add some files and descriptions. So far everything is Good. But the problem comes when I click on the launch modal button (add the file here), I'm unable to pass the id to the Modal. I tried to set a value to a variable using the useState hook but it will get a value only after the modal is closed.
My initials states like
const [categories, setCategories] = useState([])
const [categoryId, setCategoryId] = useState()
const [modal, setModal] = useState(false)
const toggle = (id) => {
setCategoryId(id)
setModal(!modal);
}
Then my code for showing categories
{ categories.map( cat => (
<div className="card border-0 rounded-0 img-thumbnail">
<img src={'assets/images/image_upload.jpg'} value={t._id} className="img-thumbnail" onClick={()=>toggle(cat._id)} alt="..."/>
</div>
)) }
<Modal
isOpen={modal}
toggle={toggle}
centered={true}
>
<ModalBody>
<div className="p-2">
<form>
<div className="form-group">
<input type="file" className="form-control-file" id="exampleFormControlFile1"/>
</div>
<div className="form-group">
<input type="text" className="form-control" id="exampleInputPassword1" placeholder="Caption Title"/>
</div>
<div className="form-group">
<textarea className="form-control" placeholder="Description" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<button type="submit" className="btn btn-form">Upload</button>
<span onClick={toggle} style={{cursor: 'pointer'}} className="ml-2 btn btn-form-outline">Cancel</span>
</form>
</div>
</ModalBody>
</Modal>
I'm getting the category id only after the modal is closed. How can I set the value along with modal window????
The problem here is that toggle
is also getting invoked when the modal gets opened & closed. You could have the toggle
function specifically just for the setting of the state if the modal should be closed or open and have the setting of the id
in a separate call.
const toggle = () => {
// setCategoryId(id) // remove this
setModal(!modal);
}
<img onClick={()=>{toggle(); setCategoryId(cat._id)}} />