Search code examples
solid-js

How do I replace a component in SolidJS?


I have the following app.jsx file. When it runs it appends both Hello World! and Hello Stack Overflow! to the document body. I need Hello Stack Overflow! to replace Hello World! (and ideally replacing only the differences), but I can't figure out how to do so.

import { render } from 'solid-js/web';

function HelloWorld() {
  return <div>Hello World!</div>;
}

function HelloStackOverflow() {
  return <div>Hello Stack Overflow!</div>;
}

render(() => <HelloWorld />, document.body)
render(() => <HelloStackOverflow />, document.body)

Solution

  • Use single render method but apply conditional rendering inside the root component.

    There are several ways:

    • Use Show component for true/false cases.

    https://www.solidjs.com/docs/latest/api#show https://www.solidjs.com/tutorial/flow_show

    • Use ternary operator for true/false cases:
    <div>{true ? <HelloWorld/ > : <HelloStackOverflow />}</div>
    

    You can use conditional expressions inside curly brackets, including function calls like createMemo.

    • Use Dynamic component to insert an arbitrary Component or tag.

    https://www.solidjs.com/docs/latest/api#dynamic

    • Use Switch when there are more than 2 mutual exclusive conditions.

    https://www.solidjs.com/docs/latest/api#switchmatch