EN VI

Javascript - How to handle the states when disabling my component in react?

2024-03-13 09:30:04
Javascript - How to handle the states when disabling my component in react?

what I want is to make the TextPanel disabled if payStub has a value, and not be disabled if payStub does not have a value,

In my react code, I have the following:

    const [payStub, setPayStub] = useState(() => {
            if (isNewPayStub) {
                return get(user, 'stub', '');
            }
            return stubEdit.value?.name || '';
        }); 

const stubIsValid = Boolean(trim(payStub));

and in the react side I have the following:

return (
        <Panel
            onClose={onClose}
            onSave={handleSave}
            addNewText={isNewPayStub ? 'Add New PayStub' : ''}
        >
        
        ....
        
        <TextPanel
                    handleChange={setPayStub}
                    isValid={stubIsValid}
                    isRequired
                    label="Stub"
                    placeholder="Enter STUB"
                    value={payStub}
                />

The TextPanel receives a property of disabled , and when I add a property as disabled: {stubIsValid}, when the user enters the first character, the condition will be met and it makes the TextPanel disabled which is not what I want (user should be able to fill enter the payStub) . How do I fix this situation?

Solution:

You can try this.

#create new variable to set the disabled value;
const [isDisabled, setIsDisabled] = useState(payStub ? true : false);


#Then create a onblur function
const handleBlur = (e) => {
        let val = e.target.value;

            if(val){
                setIsDisabled(true)
            }else{
                setIsDisabled(false)
            }          
    };

#Then on your TextPanel you can add this. This is to handle the disabled element whether your payStub variable has value or none.

<TextPanel
    handleChange={setPayStub}
    isValid={stubIsValid}
    isRequired
    label="Stub"
    placeholder="Enter STUB"
    value={payStub}
    onBlur={handleBlur}
    disabled = {isDisabled}
/>

Hope it will help.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login