2

My hook function

 function useFormInput(initialValue){
   const [value, setValue] = useState(initialValue);
   function handleChange(e){
   setValue(e.target.value);
                           }
    return {
          value,
          onChange: handleChange
         };
    }

The way I called them independently inside a main function.

    const name = useFormInput('Aziyat');
    const rating = useFormInput('10');

As far as I understood, it automatically setValue when I declare them as name and rating(above code).

If I want to change the state of name and rating how do I do? Also, how can I use handleChange outside of the function?

1 Answer 1

3

From useFormInput() hook, you're returning an object {value,onChange} properties. You can simply destructure them like so

 const {value,onChange }= useFormInput('Aziyat');

// if useFormInput has to be used multiple times in same scope, you can do this way
// Now, to access rating, you will use rating const and to change rating you can use onChangeRating function

 const {value:rating,onChange:onChangeRating} = useFormInput('10');

Sign up to request clarification or add additional context in comments.

7 Comments

hey, thank you for your reply. Let's say I want to setValue of the name, and rating to ("") empty string after rendering them , how do I do that?
you can do that using useEffect. First, I want to know are you going to use state changer functions on an input or you're going to use them anywhere else too? I'll add the solution according to that @MarkEzberg
I will use in input form. Would be great!
@MarkEzberg Check this CodeSandbox
oh ok. If you're calling onChange() function anywhere else, then I'd have done it another way. But for your use case this is best approach, @MarkEzberg
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.