Home > Mobile >  Conditional Rendering not responding in React Native
Conditional Rendering not responding in React Native

Time:09-09

I am having trouble with my conditional statement. It only ever renders true even when it is false. I have a jobs list page that when pressed sets the 'selectedJob.' That job is then presented in a modal where you can save the job or remove it. But if the job is already been saved then I need the correct button to be displayed.

  const [saved, setSaved] = useState(null);

  useEffect(() => {
    setSaved(selectedJob.saved);
  }, [selectedJob]);

            {saved ? (
              <Button
                onPress={() => removeJob(selectedJob)}
                btnTxt={"Saved"}
              />
            ) : (
              <Button
                onPress={() => saveJob(selectedJob)}
                btnTxt={"Save"}
              />
            )}

CodePudding user response:

If you use boolean as a string like 'true' and 'false' it compares as string not boolean so as long as it's value is not null or undefined or '' it will be considered as true so either you should change your server to use boolean values instead of string or you can match string in condition like

        {saved == 'true' ? (
          <Button
            onPress={() => removeJob(selectedJob)}
            btnTxt={"Saved"}
          />
        ) : (
          <Button
            onPress={() => saveJob(selectedJob)}
            btnTxt={"Save"}
          />
        )}
  • Related