Nikoloz Chichua
Nikoloz Chichua

Reputation: 15

Is this a good practice in using the useState hook in a component to pass values to the parent of the component?

I am trying to create an Input component that can be used dynamically in any page which stores the input value and has an attribute getValue which lets the parent of the component access it. In App.js I have an object called "info" that stores the values taken from the Input component. Is the following code a good implementation for this problem?

Input.js

const Input = ({placeholder, getValue}) => (
    <input 
        placeholder={placeholder} 
        onChange={({target}) => getValue(target.placeholder, target.value)} 
    />
)

Input.defaultProps = {
    getValue: (key, value) => {}
}

export default Input;

App.js

import { useState } from "react";
import Input from "./Input.js";

const App = () => {
    const [info, setInfo] = useState({});

    const addToInfo = (name, val) => {
        let keyWord = (name.charAt(0).toLowerCase() + name.slice(1)).replace(/\s/g, "");
        setInfo(prev => ({...prev, [keyWord]: val}))
    }

    return (
        <div>
            <h1>Hello {info.firstName && info.firstName} {info.lastName && info.lastName}</h1>
            <Input placeholder="First Name" getValue={(name, val) => addToInfo(name, val)}/>
            <br/>
            <Input placeholder="Last Name" getValue={(name, val) => addToInfo(name, val)}/>
            <br/>
            <Input placeholder="Email" getValue={(name, val) => addToInfo(name, val)}/>
            <br/>
            <Input placeholder="Phone Number" getValue={(name, val) => addToInfo(name, val)}/>
            <br/>
            <button onClick={() => console.log(info)}>Console Log the Info</button>
        </div>
    );
}

export default App;

Upvotes: 0

Views: 74

Answers (1)

Enfield Li
Enfield Li

Reputation: 2530

I recommend you can take a look at Formik, their approach is exactly the solution to your problem, namely, passing value up to a parent, here's the basic structure they use:

<Formik>
{(props) => (
    <Form>  // This is from Formik
    // your basic form stuff
    </Form>
)}
</Formik>

On how to make the <Form></Form> reusable, last time I asked one of their contributor on it, feel free to take a look: Make Formik a custom component

This is Formik official website Hope this can help you draw some inspiration!

Upvotes: 1

Related Questions