1

This question may sound silly, but it would help me a lot in my React projects and it would significantly reduce amount of code.

I have some code like following:

const [user, setUser] = useState({
      name: "",
      password: ""
      });

const [name, setName] = useState("");
const [password, setPassword] = useState("");

const handleInput = (e) => {  

I would like to do this

      let inputHandler =`set${(e.target.name.slice(0,1)).toUpperCase()}${e.target.name.slice(1)}`;
      inputHandler(e.event.value);

like I am doing this

      setUser({...user,
           [e.target.name]:e.target.value
      });

};

<input onChange={handleInput} name="name"></input>
<input onChange={handleInput} name="password"></input>
           

The point is to update different states "genericly", like I am doing with one state properties. The code above is really simplified, in my project there are 10+ states to handle and I achieved that with 200 lines of code :D

1 Answer 1

1

Just pass a callback to your "generic function":

const handleInput = (e, set) => {
  set(`${e.target.name.slice(0, 1).toUpperCase()}${e.target.name.slice(1)}`);
};

// Usage
onClick={e => handleInput(e, setUser)}

// Or as curried function
const genInputHandler = set => e => {
  set(`${e.target.name.slice(0, 1).toUpperCase()}${e.target.name.slice(1)}`);
};

// Usage
onClick={genInputHandler(setUser)}
Sign up to request clarification or add additional context in comments.

Comments

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.