Search code examples
javascriptreactjsreact-nativepromptformik

Access the FORMIK form fields values of a child component from it's parent component - React JS


I am using Formik for form validation in React application. Parent component (Users) - displays list of users. If we select any user, details of the user will be displayed in another component to the right side in a form. The child component (UserDetails) displays the details of the selected user. All the details are displayed in textboxes in child component, which we can change and update the details(Here I am using FORMIK to validate fields before updating).

I have a scenario where when someone modifies the details in the form and clicks on another user without updating previous edits. In such cases I want to show a prompt stating that "unsaved changes will be lost"


Solution

  • Doesn't look like there's a prop on <Formik/> to be notified of changes. From looking at the API, you could store a flag on Users that is toggled on any change from the currently presented form:

    // Users
    
    function Users() {
        const [edited, setEdited] = useState(false);
        const [active, setActive] = useState();
        return (
            <>
                <UsersList onSelect={(user) => {
                    if (edited) {
                        // Notify user of unsaved changes
                    } else {
                        setEdited(false);
                        setActive(user);
                    }
                }}/>
                <UserDetails user={active} onEdit={() => setEdited(true)}/>
            </>
        )
    }
    
    // UserDetails
    
    function UserDetails({ onEdit }) {
        return (
            <Formik>
                {props => (
                    <input onChange={(evt) => {
                        onEdit(); // Notify parent component of an edit
                        props.handleChange(evt);
                    }}/>
                )}
            </Formik>
        )
    }