I was trying to make a select appear whenever the value of the variable isDisabled is set to false, however no change to the html is made, I have tried to change the html dynamically in several ways this was the last and least messy attempt, but no it worked anyway. What I expect is that whenever I select some type of person (PF or PJ) the respective select box appears.
export default function App() {
let isDisabled = true;
let isDisabledPF = true;
function showOptions(value) {
if (value === 'PF') {
isDisabled = false;
isDisabledPF = false;
} else if (value === 'PJ') {
isDisabled = false;
isDisabledPF = true;
} else {
isDisabled = true;
}
}
return (
<div>
<form action="">
<div>
<div>
<h4>Selecione a opção que melhor te define:</h4>
<div>
<select defaultValue={null}
onChange={(e) => { showOptions(e.target.value) }}>
<option value="none"></option>
<option value="PF">Pessoa Física</option>
<option value="PJ">Pessoa Jurídica</option>
</select>
</div>
</div>
{(isDisabled) ? <></> : (isDisabledPF) ? (
<>
<select>
<option value="none"></option>
<option value="fotografo">Fotógrafo</option>
</select>
</>
) : (
<>
<select>
<option value="none"></option>
<option value="turismo">Agência de Turismo</option>
</select>
</>
)}
<button type='submit'>
Enviar
</button>
</div>
</form>
</div>
)
}
>Solution :
What you’re missing is a critical and fundamental concept in React… state.
Don’t use a normal variable, use a state value:
const [isDisabled, setIsDisabled] = useState(true);
const [isDisabledPF, setIsDisabledPF] = useState(true);
Then you can update state in your function by calling the set* functions above, for example:
if (value === 'PF') {
setIsDisabled(false);
setIsDisabledPF(false);
}
// etc.
Updating state will trigger the component to re-render, and the new render will have the new state values to produce the updated result.
Otherwise, while your current code does successfully update the values of your variables, what it doesn’t do is trigger React to re-render anything.