Home > Software design >  Why doesn't this toggle visibility of React-Native component?
Why doesn't this toggle visibility of React-Native component?

Time:06-21

I'm new to React-Native and looking for a simple, straightforward way to toggle visibility of elements. Why won't this code of mine show/hide the icon? It's a simple useState and useEffect right?

const [isDisabled, setIsDisabled] = React.useState('opacity:0')
React.useEffect(() => {
        const emailIsValid = regexEmail.test(email)
        console.log(emailIsValid)
        if(emailIsValid) {
            setIsDisabled('opacity:0')
        } else {
            setIsDisabled('opacity:100')
        }
        
    }, [email])

return (
        
        <View style={styles.container}>
            
            
            <TextInput 
                style={styles.textInput}
                placeholder="Email address"
                value = {email}
                onChangeText={text=>setEmail(text)} />

            <EvilIcons name="exclamation" size={24} color="orange" style={{isDisabled}}/> /*this one!*/
             

            <TextInput 
                style={styles.textInput}
                placeholder="Password"
                value={password}
                onChangeText={text=>setPassword(text)}
                secureTextEntry />
            
            <TextInput 
                style={styles.textInput}
                placeholder="Confirm password"
                value={confirmPassword}
                onChangeText={text=>setConfirmPassword(text)}
                secureTextEntry />

            <Button 
                disabled={submitDisabled}
                style={styles.buttonLogin}
                title='Register'
                onPress={submitRegister} />
   
        </View>
        
    ) 

CodePudding user response:

You should not think of it as styles but rather as conditions. Here's an example with a boolean.

const [isDisabled, setIsDisabled] = React.useState(true)

//...

{isDisabled && <EvilIcons name={"exclamation"} size={24} color={"orange"} />}

If you really want to use styles to show/hide the element, you should pass an object to the styles property instead of a string, that's why it isn't working in your example. The styles parameter takes an object not string.

const [isDisabled, setIsDisabled] = React.useState({opacity:0})

//...

<EvilIcons name={"exclamation"} size={24} color={"orange"} style={isDisabled} />

Finally, I think that you must use {} to wrap string type parameters on your EvilIcons component.

CodePudding user response:

The opacity value on your useState is a string, it needs to be a number.

  const [isDisabled, setIsDisabled] = React.useState(0);

  if(emailIsValid) {
    setIsDisabled(0);
  } else {
    setIsDisabled(100);
  }

// ...
return (
  <EvilIcons name="exclamation" size={24} color="orange" style={{ opacity: isDisabled }}/>
);
  • Related