Goune Kenfack
Goune Kenfack

Reputation: 117

Why can't I show my solid-js button using the <Show> conditional method after I assign a value to my variable?

I work in solid-js. I created in my project a url variable. My application must display a chat creation button to the user if the value does not the url variable exists and a message You cannot create a whelpschat if the variable has a null value. For this, I created a conditional structure in solid-js:

<Show when={open()}>

         <Show when={url()?.trim().length}>
              ...
           <CreateChat/>
             ...
         </Show>
         <Show when={!url()?.trim().length}>
                ...
         You cannot create a whelpschat 
             ...
         </Show>
</Show>

When I test, when the url variable has a null value, it displays the message You cannot create a whelpschat; but when I assign a value to the url variable for example banana, it always displays the message instead of the button. However, given that the variable does indeed have a non-zero value, it is the button that should normally have been displayed. I don't understand why this isn't working. I hope I can get help from more experienced members of the community. Thanks !

Upvotes: 1

Views: 929

Answers (2)

snnsnn
snnsnn

Reputation: 13698

Your rendering logic is wrong: You are rendering both the CreateChat component and fallback component at the same time. To fix it, use a single Show component providing a condition and a fallback.

<Show when={url()?.trim().length} fallback={<div>Invalid URL</div>}>
  <CreateChat/>
</Show>

Alternatively you can employ a simple if statement in your JSX:

const CustomComponent = () => {
  if(url().trim().length) {
    return <CreateChat />
  }

  return <div>Invalid URL</div>
}

Upvotes: 0

Edlingao
Edlingao

Reputation: 156

Try using the fallback prop

The fallback on SolidJS is kind of like an else statement on plain js, whenever your condition is false it will always render the fallback, if the condition is true then it'll render all the children of the Show component

Instead of this

     <Show when={url()?.trim().length}>
          ...
       <CreateChat/>
         ...
     </Show>
     <Show when={!url()?.trim().length}>
            ...
     You cannot create a whelpschat 
         ...
     </Show>

Do this

     <Show when={url()?.trim().length}
       fallback={<p>You cannot create a whelpschat</p>}  
     >
          ...
       <CreateChat/>
         ...
     </Show>

Upvotes: 2

Related Questions