luwes / sinuous

🧬 Light, fast, reactive UI library
https://sinuous.netlify.app
1.05k stars 34 forks source link

Conditional Rendering #6

Closed andymans closed 4 years ago

andymans commented 5 years ago

Does an ${if...} ${if...else} exist?

luwes commented 5 years ago

There are no extra tags but yes this is possible in the expressions via plain JS.

I put together an example here. https://codesandbox.io/s/vigilant-elgamal-nx8nn

const template = () => {
  return html`
    <div style=${style}>
      Sinuous
      ${() =>
        count() >= 3
          ? html`<b> count ${count}</b>`
          : html`<b> cool</b>`
       }
    </div>
  `;
};
andymans commented 5 years ago

Thanks!

dpamp commented 5 years ago

Does an ${if...} ${if...else} exist?

I modified the example with if and return statements and works too

const template = () => {
  return html`
    <div style=${style}>
      Sinuous
      ${() =>{
        if (count() >= 3) {
         return html`
         <b> count ${count}</b>
       `
        } else {          
          return html`
              <b> cool</b>
            `
        }
      } 
      }
    </div>
  `;
ryansolid commented 4 years ago

It is worth pointing out in all these cases that as count goes to 4, 5, 6, 7, 8 ... You will redoing the work and recreating that template over an over. For a simple case like this that is no problem, but if you have to be careful with conditions and possibly need to hoist the condition if you don't want the parent computed to run over and over.

theSherwood commented 4 years ago

What does this look like with memoization?

luwes commented 4 years ago

something like this would work https://codesandbox.io/s/thirsty-ptolemy-89qbi

for this example that is definitely overkill I think and a simple hoist like @ryansolid suggested would be better. updated the demo with an example of this

https://codesandbox.io/s/vigilant-elgamal-nx8nn

luwes commented 4 years ago

found a slightly cleaner solution that retains the locality: https://codesandbox.io/s/elegant-neumann-mpn0u

there might be an even better one, not sure.

      html`${when(
        () => count() >= 3,
        cond =>
          cond
            ? console.log("render count") ||
              html`
                <b> count ${count}</b>
              `
            : console.log("render cool") ||
              html`
                <b> cool</b>
              `
      )}`
const when = (condition, view) => {
  const memoView = memo((...args) => root(() => view(...args)));
  return () => memoView(condition());
};
nettybun commented 4 years ago

To any future devs, this might be useful as well: https://github.com/luwes/sinuous/issues/115#issuecomment-647676837