Display different values in a popup in React - reactjs

I am trying to have a popup for editing profile information in react, and I want there to be a button by each value that will allow a user to edit that specific value. The popup works, except it will only display the last value that I have put in. I think it is because I need to reset the state each time the button is clicked, but I am still fairly new to react so I am not sure how to do it.
I will add my code, however it is pulling some information from a local database, so let me know if you need me to remove things.
Here is the component for the popup
import React from 'react'
const Popup = props => {
console.log(props)
return(
<div className='popup-box'>
<div className='box'>
<span className='close-icon' onClick={props.handleClose}>x</span>
{props.content}
</div>
</div>
)
}
export default Popup
And here is the component page where the popup appears
import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { getUser } from '../apiClient'
import Nav from './Nav'
import EditPopup from './EditPopup'
export default function UserProfile (props) {
const [isOpen, setIsOpen] = useState(false)
const togglePopup = () => {
setIsOpen(!isOpen)
}
const [user, setUser] = useState({
user: []
})
useEffect(() => {
getUser(props.match.params.id)
.then((res) => {
setUser(res)
})
.catch((error) => {
console.log('error', error.message)
})
}, [])
return (
<div className='globalBackground'>
<Nav />
<div className='UserInfoForm'>
<div className='profile-heading' >
<h1>General User Information</h1>
</div>
<div className='profile-Pic' >
<div className='profile-pic-heading'>
<h2>Profile Picture</h2>
</div>
<div className='profile-pic-display'>
<img src={user.profilePic} style={{ width: '150px', height: '150px' }}
alt=''
/>
</div>
</div>
<div className='UsernameEdit'>
<h2>Username</h2>
<p>{user.username}</p>
<input type='button' value='Edit' onClick={togglePopup} />
{isOpen && <EditPopup
content={<>
<b>Edit Your Username</b>
<div className='userNameEditInput'>
<input className='usernameEdit' placeholder={user.username} />
</div>
<button>Save Changes</button>
</>}
handleClose={togglePopup}
/>}
<div />
<div className='EmailEdit'>
<h2>Email</h2>
<p>{user.email}</p>
<input type='button' value='Edit' onClick={togglePopup} />
{isOpen && <EditPopup
content={<>
<b>Edit Your Email</b>
<div className='emailEditInput'>
<input className='emailEdit' placeholder={user.email} />
</div>
<button>Save Changes</button>
</>}
handleClose={togglePopup}
/>}
</div>
<div className='CountryEdit'>
<h2>Country</h2>
<p>{user.country}</p>
<input type='button' value='Edit' onClick={togglePopup} />
{isOpen && <EditPopup
content={<>
<b>Edit Your Country</b>
<div className='countryEditInput'>
<input className='countryEdit' placeholder={user.country} />
</div>
<button>Save Changes</button>
</>}
handleClose={togglePopup}
/>}
</div>
<div className='RegionEdit'>
<h2>Region</h2>
<p>{user.region}</p>
<input type='button' value='Edit' onClick={togglePopup} />
{isOpen && <EditPopup
content={<>
<b>Edit Your Region</b>
<div className='regionEditInput'>
<input className='regionEdit' placeholder={user.email} />
</div>
<button>Save Changes</button>
</>}
handleClose={togglePopup}
/>}
</div>
<div className='HandicapEdit'>
<h2>Handicap</h2>
<p>{user.handicap}</p>
<input type='button' value='Edit' onClick={togglePopup} />
{isOpen && <EditPopup
content={<>
<b>Edit Your Handicap</b>
<div className='handicapEditInput'>
<input className='handicapEdit' placeholder={user.handicap} />
</div>
<button>Save Changes</button>
</>}
handleClose={togglePopup}
/>}
</div>
</div>
</div>
</div>
)
}
Let me know if there's any other code needed, any help would be greatly appreciated :--)

You can remove the state from the UserProfile and move it inside the Popup Component.
import React from 'react';
const Popup = (props) => {
const [toggle, setToggle] = useState(false);
const togglePopup = () => setToggle((prevToggle) => !prevToggle);
return (
<>
<input type="button" value="Edit" onClick={togglePopup} />
{toggle && (
<div className="popup-box">
<div className="box">
<span className="close-icon" onClick={togglePopup }>
x
</span>
{props.content}
</div>
</div>
)}
</>
);
};
export default Popup;
You can then use EditPopup as below in the UserProfile.
{
<div className='UsernameEdit'>
<h2>Username</h2>
<p>{user.username}</p>
<EditPopup
content={<>
<b>Edit Your Username</b>
<div className='userNameEditInput'>
<input className='usernameEdit' placeholder={user.username} />
</div>
<button>Save Changes</button>
</>
}
/>
<div />
}

Related

How to call a modal from an onClick event

Trying to trigger a modal popup from an onClick event as below:
import {KTSVG} from '../../../../../../../_metronic/helpers'
import {useListView} from '../../core/ListViewProvider'
import { CreateAppModal } from '../../manage-properties-modal/add-property-modal/AddPropertyModal'
// import {UsersListFilter} from './UsersListFilter'
const PropertyListToolbar = () => {
const {setItemIdForUpdate} = useListView()
const openAddUserModal = () => {
setItemIdForUpdate(null)
}
return (
<div className='d-flex justify-content-end' data-kt-user-table-toolbar='base'>
{/* <UsersListFilter /> */}
{/* begin::Export */}
{/* <button type='button' className='btn btn-light-primary me-3' onClick={openAddUserModal}>
<KTSVG path='/media/icons/duotune/arrows/arr078.svg' className='svg-icon-2' />
Export Details
</button> */}
{/* end::Export */}
{/* begin::Add user */}
<button type='button' className='btn btn-primary' onClick={CreateAppModal}>
<KTSVG path='/media/icons/duotune/arrows/arr075.svg' className='svg-icon-2' />
New Property
</button>
{/* end::Add user */}
</div>
)
}
export {PropertyListToolbar}
The setItemIdForUpdate code, I would like to just disable for now and just get the button to launch the below modal, which I can then customize before I look at saving its state.
import {useState, useRef} from 'react'
import {createPortal} from 'react-dom'
import {Modal} from 'react-bootstrap'
import {defaultCreateAppData, ICreateAppData} from './IAppModels'
import {StepperComponent} from '../../../assets/ts/components'
import {KTSVG} from '../../../helpers'
import {Step1} from './steps/Step1'
import {Step2} from './steps/Step2'
import {Step3} from './steps/Step3'
import {Step4} from './steps/Step4'
import {Step5} from './steps/Step5'
type Props = {
show: boolean
handleClose: () => void
}
const modalsRoot = document.getElementById('root-modals') || document.body
const CreateAppModal = ({show, handleClose}: Props) => {
const stepperRef = useRef<HTMLDivElement | null>(null)
const stepper = useRef<StepperComponent | null>(null)
const [data, setData] = useState<ICreateAppData>(defaultCreateAppData)
const [hasError, setHasError] = useState(false)
const loadStepper = () => {
stepper.current = StepperComponent.createInsance(stepperRef.current as HTMLDivElement)
}
const updateData = (fieldsToUpdate: Partial<ICreateAppData>) => {
const updatedData = {...data, ...fieldsToUpdate}
setData(updatedData)
}
const checkAppBasic = (): boolean => {
if (!data.appBasic.appName || !data.appBasic.appType) {
return false
}
return true
}
const checkAppDataBase = (): boolean => {
if (!data.appDatabase.databaseName || !data.appDatabase.databaseSolution) {
return false
}
return true
}
const prevStep = () => {
if (!stepper.current) {
return
}
stepper.current.goPrev()
}
const nextStep = () => {
setHasError(false)
if (!stepper.current) {
return
}
if (stepper.current.getCurrentStepIndex() === 1) {
if (!checkAppBasic()) {
setHasError(true)
return
}
}
if (stepper.current.getCurrentStepIndex() === 3) {
if (!checkAppDataBase()) {
setHasError(true)
return
}
}
stepper.current.goNext()
}
const submit = () => {
window.location.reload()
}
return createPortal(
<Modal
id='kt_modal_create_app'
tabIndex={-1}
aria-hidden='true'
dialogClassName='modal-dialog modal-dialog-centered mw-900px'
show={show}
onHide={handleClose}
onEntered={loadStepper}
>
<div className='modal-header'>
<h2>Create App</h2>
{/* begin::Close */}
<div className='btn btn-sm btn-icon btn-active-color-primary' onClick={handleClose}>
<KTSVG className='svg-icon-1' path='/media/icons/duotune/arrows/arr061.svg' />
</div>
{/* end::Close */}
</div>
<div className='modal-body py-lg-10 px-lg-10'>
{/*begin::Stepper */}
<div
ref={stepperRef}
className='stepper stepper-pills stepper-column d-flex flex-column flex-xl-row flex-row-fluid'
id='kt_modal_create_app_stepper'
>
{/* begin::Aside*/}
<div className='d-flex justify-content-center justify-content-xl-start flex-row-auto w-100 w-xl-300px'>
{/* begin::Nav*/}
<div className='stepper-nav ps-lg-10'>
{/* begin::Step 1*/}
<div className='stepper-item current' data-kt-stepper-element='nav'>
{/* begin::Wrapper*/}
<div className='stepper-wrapper'>
{/* begin::Icon*/}
<div className='stepper-icon w-40px h-40px'>
<i className='stepper-check fas fa-check'></i>
<span className='stepper-number'>1</span>
</div>
{/* end::Icon*/}
{/* begin::Label*/}
<div className='stepper-label'>
<h3 className='stepper-title'>Details</h3>
<div className='stepper-desc'>Name your App</div>
</div>
{/* end::Label*/}
</div>
{/* end::Wrapper*/}
{/* begin::Line*/}
<div className='stepper-line h-40px'></div>
{/* end::Line*/}
</div>
{/* end::Step 1*/}
{/* begin::Step 2*/}
<div className='stepper-item' data-kt-stepper-element='nav'>
{/* begin::Wrapper*/}
<div className='stepper-wrapper'>
{/* begin::Icon*/}
<div className='stepper-icon w-40px h-40px'>
<i className='stepper-check fas fa-check'></i>
<span className='stepper-number'>2</span>
</div>
{/* begin::Icon*/}
{/* begin::Label*/}
<div className='stepper-label'>
<h3 className='stepper-title'>Frameworks</h3>
<div className='stepper-desc'>Define your app framework</div>
</div>
{/* begin::Label*/}
</div>
{/* end::Wrapper*/}
{/* begin::Line*/}
<div className='stepper-line h-40px'></div>
{/* end::Line*/}
</div>
{/* end::Step 2*/}
{/* begin::Step 3*/}
<div className='stepper-item' data-kt-stepper-element='nav'>
{/* begin::Wrapper*/}
<div className='stepper-wrapper'>
{/* begin::Icon*/}
<div className='stepper-icon w-40px h-40px'>
<i className='stepper-check fas fa-check'></i>
<span className='stepper-number'>3</span>
</div>
{/* end::Icon*/}
{/* begin::Label*/}
<div className='stepper-label'>
<h3 className='stepper-title'>Database</h3>
<div className='stepper-desc'>Select the app database type</div>
</div>
{/* end::Label*/}
</div>
{/* end::Wrapper*/}
{/* begin::Line*/}
<div className='stepper-line h-40px'></div>
{/* end::Line*/}
</div>
{/* end::Step 3*/}
{/* begin::Step 4*/}
<div className='stepper-item' data-kt-stepper-element='nav'>
{/* begin::Wrapper*/}
<div className='stepper-wrapper'>
{/* begin::Icon*/}
<div className='stepper-icon w-40px h-40px'>
<i className='stepper-check fas fa-check'></i>
<span className='stepper-number'>4</span>
</div>
{/* end::Icon*/}
{/* begin::Label*/}
<div className='stepper-label'>
<h3 className='stepper-title'>Storage</h3>
<div className='stepper-desc'>Provide storage details</div>
</div>
{/* end::Label*/}
</div>
{/* end::Wrapper*/}
{/* begin::Line*/}
<div className='stepper-line h-40px'></div>
{/* end::Line*/}
</div>
{/* end::Step 4*/}
{/* begin::Step 5*/}
<div className='stepper-item' data-kt-stepper-element='nav'>
{/* begin::Wrapper*/}
<div className='stepper-wrapper'>
{/* begin::Icon*/}
<div className='stepper-icon w-40px h-40px'>
<i className='stepper-check fas fa-check'></i>
<span className='stepper-number'>5</span>
</div>
{/* end::Icon*/}
{/* begin::Label*/}
<div className='stepper-label'>
<h3 className='stepper-title'>Completed</h3>
<div className='stepper-desc'>Review and Submit</div>
</div>
{/* end::Label*/}
</div>
{/* end::Wrapper*/}
</div>
{/* end::Step 5*/}
</div>
{/* end::Nav*/}
</div>
{/* begin::Aside*/}
{/*begin::Content */}
<div className='flex-row-fluid py-lg-5 px-lg-15'>
{/*begin::Form */}
<form noValidate id='kt_modal_create_app_form'>
<Step1 data={data} updateData={updateData} hasError={hasError} />
<Step2 data={data} updateData={updateData} hasError={hasError} />
<Step3 data={data} updateData={updateData} hasError={hasError} />
<Step4 data={data} updateData={updateData} hasError={hasError} />
<Step5 />
{/*begin::Actions */}
<div className='d-flex flex-stack pt-10'>
<div className='me-2'>
<button
type='button'
className='btn btn-lg btn-light-primary me-3'
data-kt-stepper-action='previous'
onClick={prevStep}
>
<KTSVG
path='/media/icons/duotune/arrows/arr063.svg'
className='svg-icon-3 me-1'
/>{' '}
Previous
</button>
</div>
<div>
<button
type='button'
className='btn btn-lg btn-primary'
data-kt-stepper-action='submit'
onClick={submit}
>
Submit{' '}
<KTSVG
path='/media/icons/duotune/arrows/arr064.svg'
className='svg-icon-3 ms-2 me-0'
/>
</button>
<button
type='button'
className='btn btn-lg btn-primary'
data-kt-stepper-action='next'
onClick={nextStep}
>
Next Step{' '}
<KTSVG
path='/media/icons/duotune/arrows/arr064.svg'
className='svg-icon-3 ms-1 me-0'
/>
</button>
</div>
</div>
{/*end::Actions */}
</form>
{/*end::Form */}
</div>
{/*end::Content */}
</div>
{/* end::Stepper */}
</div>
</Modal>,
modalsRoot
)
}
export {CreateAppModal}
I would like to trigger CreateAppModal but cannot for the life of me get my head around it. Any help would be greatly appreciated!
You need to share the source code from CreateAppModal so we can know what it does and whats the relation with setItemIdForUpdate.

How to upload two images in same react form in formik and yup not multiple images

I am new to React. I have one form with three images, form works perfectly with one image but when try to upload image in second box with same code it took the first image. I did copy and Paste the first image upload code for second box. now the problem is when I try to upload image in second box same image also get uploaded in first box. here is what I have tried so far
import "./influencerPersonalInfo.css";
import { Dropdown } from "semantic-ui-react";
import AddBoxIcon from "#mui/icons-material/AddBox";
import { personalValidation } from "../../../../validation/Validation";
import { ErrorMessage, Formik, Form, Field } from "formik";
import HeaderNinfo from "../../HeaderNinfo";
import {ImagePreview,ImagePreviewTwo} from "../../ImagePreview";
import Dropzone from "react-dropzone";
const InfluencerPersonalInfo = () => {
const [file, setFile] = React.useState(null)
const fileRefOne = useRef(null)
const fileRefTwo = useRef(null)
const fileHandler = (e) => {
setFile(e.target.files[0])
}
const defaultValue = {
fullName: "",
stageName: "",
gender: "",
languages: "",
location: "",
description: "",
file:null,
};
const handleSubmit = (values) => {
console.log({
values
});
}
return (
<div className="row">
<Formik
initialValues={defaultValue}
validationSchema={personalValidation}
onSubmit={handleSubmit}
>
{({ values, setFieldValue }) => (
<Form>
<div className="col-xxl-6 col-lg-7 col-md-10">
<h3 className="mb-2">Profile Photo*</h3>
<p className="mb-3">Add at least 3 Photo to continue</p>
<div className="row profile-img">
<div className="col-xxl-4 col-lg-4 col-6 mb-4">
<div className="img-show">
{values.file && <ImagePreview file={values.file} />}
<div className="cancelbtn" id="cancelbtn">
<i className="fa-solid fa-rectangle-xmark fs-3"></i>
</div>
<div className="icons">
<p>{values.file ? "" : "No File chosen"}</p>
</div>
<input
accept="image/*"
ref={fileRefOne}
hidden
multiple
type="file"
onChange={(event)=>{
setFieldValue("file",event.currentTarget.files[0]);
}}
/>
<span className="btn-upload" >
<AddBoxIcon onClick={()=>{
fileRefOne.current.click();
}}></AddBoxIcon>
</span>
</div>
<span className="text-danger">
<ErrorMessage name="file" />
</span>
</div>
<div className="col-xxl-4 col-lg-4 col-6 mb-4">
<div className="img-show">
{values.file && <ImagePreview file={values.file} />}
<div className="cancelbtn" id="cancelbtn">
<i className="fa-solid fa-rectangle-xmark fs-3"></i>
</div>
<div className="icons">
<p>{values.file ? "" : "No File chosen"}</p>
</div>
<input
accept="image/*"
ref={fileRefTwo}
hidden
type="file"
onChange={(event)=>{
setFieldValue("file", ...event.currentTarget.files[0]);
}}
/>
<span className="btn-upload" >
<AddBoxIcon onClick={()=>{
fileRefTwo.current.click();
}}></AddBoxIcon>
</span>
</div>
<span className="text-danger">
<ErrorMessage name="file" />
</span>
</div>
<div className="col-xxl-4 col-lg-4 col-6 mb-4">
<div className="img-show">
<img src="" alt="" className="img-fluid" />
<div className="cancelbtn" id="cancelbtn">
<i className="fa-solid fa-rectangle-xmark fs-3"></i>
</div>
<div className="icons">
<i className="fa-solid fa-cloud-arrow-up"></i>
<p>No File chosen</p>
</div>
<button className="btn-upload">
<i className="fa-solid fa-plus"></i>
</button>
</div>
<input type="file" className="default-btn" hidden />
</div>
<div className="col-xxl-4 col-lg-4 col-6 mb-4">
<div className="img-show">
<img src="" alt="" className="img-fluid" />
<div className="cancelbtn" id="cancelbtn">
<i className="fa-solid fa-rectangle-xmark fs-3"></i>
</div>
<div className="icons">
<i className="fa-solid fa-cloud-arrow-up"></i>
<p>No File chosen</p>
</div>
<button className="btn-upload">
<i className="fa-solid fa-plus"></i>
</button>
</div>
<input type="file" className="default-btn" hidden />
</div>
<div className="text-end mt-5">
<button className="btn-form" type="submit">
Continue
</button>
</div>
</Form>
)}
</Formik>
</div>
)
export default InfluencerPersonalInfo;
validation code
const SUPPORTED_FORMATS = ["image/jpg", "image/jpeg", "image/png"]
export const personalValidation = yup.object().shape({
fullName: yup.string().required('Full name is required').nullable(),
stageName: yup.string().required('Stage Name is required'),
gender:yup.string().required('Gender is required'),
languages:yup.array().min(1).required('Select atleast one language'),
location:yup.string().required('Location is required'),
description:yup.string().required('Location is required'),
file:yup.mixed().nullable().required('This picture is required').test(
"FILE_SIZE",
"Uploaded file is too big",
(value)=>!value||(value && value.size<=1024*1024)
).test(
"FILE_FORMAT",
"Uploaded file has unsupported format",
(value)=>!value||(value && SUPPORTED_FORMATS.includes(value?.type))
)
})
ImagePreview code
import React,{ useState } from "react";
export const ImagePreview = ({file}) => {
const [preview, setPreview] = React.useState(null);
const renderOne = new FileReader();
renderOne.readAsDataURL(file);
renderOne.onload = ()=>{
setPreview(renderOne.result);
}
return (
<div>
<img src={preview} alt="preview" className="img-fluid" />
</div>
)
}

How can I display my data dynamically onclick event in React

I'm creating a movies app with React and Redux, in each movie card I have some information about the movie like the title, image, and a button(buy a ticket). The idea is when I click on the button of each card I want to get the same image and title of the card and display it on the same page on another card that going to pop up so the user can choose the quantity and continue.
How can I get the data from the movie card onclick and transform it to another card as a pop-up?
what do you think
Single movie card Component
const SingleMovieCard = ({ id, title, poster_path, overview, toggleHandler }) => {
const [selected, isSelected] = useState(null);
return (
<article key={id} className="card">
<div key={id} onMouseEnter={() => isSelected(id)} onMouseLeave={() => isSelected(null)}>
<img src={`${ImgPath}` + poster_path} alt={title} className="image" />
{selected === id && <video src="./Trailers/SpaceJam.mp4" autoPlay={true} loop muted />}
</div>
<div className="body-card">
<h1>{title}</h1>
<p>{`${overview.substring(0, 200)}...`}</p>
</div>
<div className="services">
<FiShare2 className="icon" />
<FiHeart className="icon" />
<div className="btn-icon-container">
<BiShoppingBag className="btn-icon" />
<button onClick={() => toggleHandler()}>Buy Ticket</button>
</div>
</div>
</article>
)
}
export default SingleMovieCard;
Pop-up movie card
const PopUpMovie = ({showClass, toggleHandler}) => {
const moviesList = useSelector((state)=> state.allMovies.movies);
return (
<div className={`pop-up-container ${showClass}`}>
<nav className="pop-up">
<GrClose className="pop-up-close" onClick={()=> toggleHandler()}/>
<div className="product-details">
<div className="img-container">
<img src="./Pictures/FreeGuy.jpg" alt="FreeGuy" />
</div>
<div className="product info">
<h1 className="title">Free Guy movie</h1>
<div className="quantity">
<h4>Quantity</h4>
<span>4</span>
</div>
<h5 className="prix">11$</h5>
<button className="btn-checkout">Continue to checkout</button>
</div>
</div>
</nav>}
</div>
)
}
export default PopUpMovie;
you can use Modal from react-bootstrap
Example:
import { Modal } from "react-bootstrap";
const PopUpMovie = ({ showClass, toggleHandler }) => {
const modalContent = (
<div className={`pop-up-container ${showClass}`}>
<nav className="pop-up">
<GrClose className="pop-up-close" onClick={() => toggleHandler()} />
<div className="product-details">
<div className="img-container">
<img src="./Pictures/FreeGuy.jpg" alt="FreeGuy" />
</div>
<div className="product info">
<h1 className="title">Free Guy movie</h1>
<div className="quantity">
<h4>Quantity</h4>
<span>4</span>
</div>
<h5 className="prix">11$</h5>
<button className="btn-checkout">Continue to checkout</button>
</div>
</div>
</nav>
</div>
)
const moviesList = useSelector((state) => state.allMovies.movies);
return (
<Modal
id="order-modal-close"
backdrop="static"
show={showClass}
size={"md"}
dialogClassName="modal-90w"
onHide={toggleHandler}
>
<Modal.Header closeButton>
<Modal.Title>Movie</Modal.Title>
</Modal.Header>
<Modal.Body >{modalContent}</Modal.Body>
{modalFooter}
</Modal>
)
}

React prevent body from scrolling if popup is open

React prevent body from scrolling if popup is open.
How can i disable the background body from scrolling when the pop up div is open.
function FilterButton() {
let [isOpen, setIsOpen] = useState(false);
return (
<div className='filter-button'>
<div className="name-filter" onClick={() => setIsOpen(!isOpen)}>
<p>Filter</p>
<i class="fas fa-filter"></i>
</div>
{
isOpen ? <div className="background-blur">
<div className="filter-popup">
<p className='filter-by-name'>Filter By Type</p>
<hr />
<div className="filter-types">
<div className="filter">
<input type="checkbox" />
<p></p>
</div>
</div>
<div className="apply-cancel">
<button className="apply">Apply</button>
<button className="cancel" onClick={() => setIsOpen(!isOpen)}>Cancel</button>
</div>
</div>
</div>
: null
}
</div>
)
}
You can use the body-scroll-lock library to help you with that.
Here is how it could work on your component. I haven't tested it tho.
import { useState, useRef, useEffect } from 'react';
import {
disableBodyScroll,
enableBodyScroll,
clearAllBodyScrollLocks
} from 'body-scroll-lock';
function FilterButton() {
const [isOpen, setIsOpen] = useState(false);
const popupRef = useRef(null)
useEffect(() => {
if (isOpen) {
popupRef.current && disableBodyScroll(popupRef.current)
} else {
popupRef.current && enableBodyScroll(popupRef.current)
}
}, [isOpen])
return (
<div className="filter-button">
<div className="name-filter" onClick={() => setIsOpen(!isOpen)}>
<p>Filter</p>
<i class="fas fa-filter"></i>
</div>
{isOpen ? (
<div className="background-blur">
<div className="filter-popup" ref={popupRef}>
<p className="filter-by-name">Filter By Type</p>
<hr />
<div className="filter-types">
<div className="filter">
<input type="checkbox" />
<p></p>
</div>
</div>
<div className="apply-cancel">
<button className="apply">Apply</button>
<button className="cancel" onClick={() => setIsOpen(!isOpen)}>
Cancel
</button>
</div>
</div>
</div>
) : null}
</div>
);
}

First key press is not working by using react hook form controlled component

I used react hook form for validations purpose. but our code is implemented on controlled components. I went through few examples in google that use default value instead of value.
If I replace the value with the default value after submitting a form. The values in the form are not clearing can anyone suggest to me how to overcome this.
import React, { useState, useEffect } from 'react';
import { getIdToken } from '../Utils/Common';
import { useForm } from 'react-hook-form';
export default function Roles() {
const [roleName, setroleName] = useState('');
const { register, handleSubmit, errors } = useForm();
const handleRoleName = (event) => {
setroleName(event.target.value);
};
const handleAddRole = () => {
/* api call here after succes i have clear role name*/
setroleName('');
};
}
return (
<div className='g-pa-20'>
<h1 className='g-font-weight-300 g-font-size-28 g-color-black g-mb-28'>
{editaddLabel}
</h1>
<form noValidate onSubmit={handleSubmit(handleAddRole)}>
<div className='row'>
<div className='col-md-4 col-xs-12 col-sm-12'>
<div className='g-brd-around g-brd-gray-light-v7 g-rounded-4 g-pa-15 g-pa-20--md g-mb-30'>
<div className='mb-4'>
<div className='form-group g-mb-30'>
<label className='g-mb-10' for='inputGroup-1_1'>
Role Name
</label>
<div
className={
errors && roleName === ''
? 'g-err-brd-primary--focus'
: 'g-pos-rel'
}
>
<span className='g-pos-abs g-top-0 g-right-0 d-block g-width-40 h-100 opacity-0 g-opacity-1--success'>
<i
className='hs-admin-check g-absolute-centered g-font-size-default g-color-secondary'
on
></i>
</span>
<input
id='inputGroup-1_1'
className='form-control form-control-md g-brd-gray-light-v7 g-brd-gray-light-v3--focus g-rounded-4 g-px-14 g-py-10'
type='text'
placeholder=''
onChange={handleRoleName}
value={roleName}
name='role'
ref={register({
required: true,
})}
/>
</div>
{errors.role && errors.role.type === 'required' && (
<p className='plans-single-error'> Role name is required.</p>
)}
</div>
</div>
<div className='from-group'>
<div className='form-row pull-right'>
<div className='form-group col-xs-6'>
<button
className='btn btn-md btn-xl--md u-btn-primary g-font-size-12 g-font-size-default--md g-mr-10 g-mb-10'
disabled={loading}
>
{loading && (
<i className='fas fa-spinner fa-spin spinner'></i>
)}
Save
</button>
</div>
<div className='form-group col-xs-6'>
<button
className='btn btn-md btn-xl--md u-btn-outline-gray-dark-v6 g-font-size-12 g-font-size-default--md g-mb-10'
onClick={cancelClick}
>
Cancel
</button>
</div>
</div>
</div>
<div className='from-group'>
<label></label>
</div>
</div>
</div>
</div>
</form>
</div>
);

Resources