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

How to conditionally render an HTML property?

On my project, I’m using PicoCSS as a default style.

I have a form on which I want to highlight the fields that have errors whenever there’s some problem while sending it.

To do that, I want to conditionally render the aria-invalid tag, because if I set it to "false", it is highlighted in green, and the behavior I want is to show only the error validation.

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

The piece of code is similar to the following:

<script>
   export let form: ActionData;
   // here I have the property "form.errors.firstName", which will be populated if I have an error
</script>
<form>
    <input name="first-name" />
    <!-->how to populate HTML property aria-invalid only if form.errors.firstName is thruty? I don't want to populate it as "aria-invalid='false'"</!-->
</form>

>Solution :

Try this:

<script>
   export let form: ActionData;
   // here I have the property "form.errors.firstName", which will be populated if I have an error
</script>
<form>
    <input name="first-name" 
           class="form-input" 
           aria-invalid="${form.errors.firstName ? 'true' : undefined}" />
</form>

Here, we are using the ternary operator to conditionally render the aria-invalid attribute. If form.errors.firstName is true, it sets the aria-invalid attribute to "true", otherwise, it sets it to undefined.

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