0

How can I swap the word email here for value??

  const [state, setState] = useState({
    emailError: '',
  });

const myFunction = (event: ChangeEvent<HTMLInputElement>) => {
   const value = event.target.id; // 'email'
   if (event.target.id === value && state.emailError) validate(value);
//                                         ^
//                                         |___ How can I swap the word email here for value??
}

I tried with this..

if (event.target.id === value && state[value]+Error) validate(value);
1
  • normally if a name is from a variable, do { [name]: value }, when you know { name: value } won't work. Commented Dec 2, 2019 at 17:58

2 Answers 2

3

You can use JS template syntax for this:

if (event.target.id === value && state[`${value}Error`]) validate(value);
Sign up to request clarification or add additional context in comments.

2 Comments

I get a typescript error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ emailError: string; }'. No index signature with a parameter of type 'string' was found on type '{ emailError: string;}'.ts(7053)
You probably need to create an interface for the state and add [key: string]: string; there: stackoverflow.com/questions/32968332/…
0

This is a tricky one since I don't think you can type the ID which would be present on the event. So you may have to explicitly type it for TS to figure it out and also add a type for your state. This may work

const [state, setState] = useState<{ emailError: string }>({
  emailError: '',
});

const myFunction = (event: ChangeEvent<HTMLInputElement>) => {
   const value = event.target.id;
   let stateKey;
   switch(value) {
     case 'email':
       stateKey = 'emailError';
       break;
   }
   if(stateKey) {
     if (event.target.id === value && state[stateKey]) validate(value);
   }
}

1 Comment

inside the switch block on statekey I get let stateKey: any ':' expected.

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.