I wish to toggle on and off the display of my <p> tag

Viewed 53

I want to toggle a <p> tag in react based on whether a link is an URL or not.

<p style={{color : "red", display : {isValid}}} >Invalid URL</p>

The function that determines the value of isValid is

const [isValid, setIsValid] = useState('none');

const isUriImage = function(uri) {
    console.log(isValid)
    setImage_url(uri.target.value);
    uri = uri.target.value;
    uri = uri.toString().split('?')[0];
    var parts = uri.split('.');
    var extension = parts[parts.length-1];
    var imageTypes = ['jpg','jpeg','tiff','png','gif','bmp']
    if(imageTypes.indexOf(extension) != -1) {
        setIsValid('none');   
        console.log("Valid")
    } else {
        setIsValid('');
        console.log("Not Valid")
    }
}

The code is working fine as I have confirmed it with the console.log statements, but my <p> tag's display is not being changed.

2 Answers

You are setting display property as and object with key isValid, instead assign isValid as variable directly

<p style={{ color: "red", display: isValid }} >Invalid URL</p>

Just to mention, in React way it would be better to not render p tag at all if you just want to hide it conditionally

Use boolean instead

const [isValid, setIsValid] = useState(false);

Render conditionally

{isValid && <p style={{ color: "red" }} >Invalid URL</p>}

In you scenario, you element display will be 'none' but it will still be in DOM. In above scenario it won't be rendered to DOM.

Just remove the extra {} around the isvalid variable.

<p style={{color : "red", display : isValid }} >Invalid URL</p>
Related