Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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", display: isValid }} >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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading