Home > Blockchain >  How to conditionally render an HTML property?
How to conditionally render an HTML property?

Time:02-05

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.

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>

CodePudding user response:

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" 
            
           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.

  • Related