What is the best way to sort through custom components within children in Solid JS?

I have been working on developing a scene switcher for my personal application, and I thought of creating a custom component called SceneSwitcher. Inside this component, I plan to add various scenes that can be rendered. Here's an example:

<SceneSwitcher>
    <LoadingScene />
    <AppScene />
    <LoginScene />
</SceneSwitcher>

SceneSwitcher.tsx

export default function SceneSwitcher() {
    const [scene, setScene] = createSignal("");

    ...

    return (
        <>
            {props.children.find(e => e.id === scene()) ?? <div></div>}
        </>
    );
}

However, I'm facing an issue where props.children.find always returns undefined, even when the value of scene() matches one of the IDs.

IDs on Scenes: LoadingScene.tsx

export default function LoadingScene() {
    ...
    return (
        <div id="loading">
            <h1>Loading content...</h1>
        </div>
    );
}

Just a few days ago, I started exploring component-style frameworks, although I have experience in programming websites using vanilla JavaScript for 4 years. This project is an opportunity for me to delve deeper into component-style frameworks and explore different approaches to problem-solving.

Answer №1

Let's start by examining the requirements:

  1. We must keep track of the active scene, which can be achieved by using a signal.
  2. We need a method to switch between different scenes, so we utilize a list of scene names with event handlers to update the active scene.
  3. A filter is required to categorize scenes based on their names and whether they are active or not. To accomplish this, we employ Switch/Match components.
const App = () => {
  const [active, setActive] = createSignal('loading');

  return (
    <div>
      <ul>
        <li onClick={() => setActive('loading')}>Loading</li>
        <li onClick={() => setActive('app')}>App</li>
        <li onClick={() => setActive('login')}>Login</li>
      </ul>
      <Switch>
        <Match when={active() === 'loading'}>
          <Loading />
        </Match>
        <Match when={active() === 'app'}>
          <App />
        </Match>
        <Match when={active() === 'login'}>
          <Login />
        </Match>
      </Switch>
    </div>
  );
};

If you are looking to implement this functionality, a router can be helpful. The URL or pathname can be used to track the active scene, while navigation can be used to switch between scenes. The Route component can associate components with specific paths.

https://github.com/solidjs/solid-router

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using VueJS to navigate to a specific route and pass parameters along with the

I'm a complete beginner when it comes to VueJS. Can someone please help me figure out how to access the deviceId in the Device component within vuejs? I've noticed that the deviceId in the h1 tag is not displaying on the Device component page. ...

Combining Multiple Properties in a Single-File Component with Vue.js 2

Currently, my project involves Laravel 5.5 & Vue.js 2.x. After extensive research and seeking answers, I began working with components. However, I am encountering a warning message upon page rendering: [Vue warn]: Property or method "trimestral" is not def ...

When running `aws-cdk yarn synth -o /tmp/artifacts`, an error is thrown stating "ENOENT: no such file or directory, open '/tmp/artifacts/manifest.json'"

Starting a new aws-cdk project with the structure outlined below src └── cdk ├── config ├── index.ts ├── pipeline.ts └── stacks node_modules cdk.json package.json The package.json file looks like this: " ...

A guide on updating URLs that are not enclosed within an anchor tag using JavaScript

In my current scenario, I am dealing with text that includes URL links presented in two different formats. www.stackoverflow.com <a href="http://www.stackoverflow.com">Stack over flow</a> My objective is to create a straightforward function ...

The ts-jest node package's spyOn method fails to match the specified overload

Currently, I'm exploring the usage of Jest alongside ts-jest for writing unit tests for a nodeJS server. My setup is quite similar to the snippet below: impl.ts export const dependency = () => {} index.ts import { dependency } from './impl.t ...

The argument provided is a string type, which cannot be assigned to a parameter expecting an object with a 'results' property of type string

When attempting to pass the result.nativeEvent.message to another function, I am encountering the error: Argument of type 'string' is not assignable to parameter of type '{ results: string; } on onUnityMessageController(result.nativeEvent.me ...

ajax fails to send the variables, instead sending undefined values

In my HTML code, I have inputs and checkboxes. The JavaScript code collects the data from the inputs, and through AJAX, it should send the information to PHP where it is received and stored in the session. However, when sending the array to the PHP file v ...

Encountering difficulties when attempting to load a module with the "js" extension in a TypeScript environment

When making a GET request with Systemjs, the extension .js is not being added to the URL. These are my TypeScript Classes customer.ts import {Address} from "./Address"; export class Customer { private _customerName: string = ""; public Customer ...

What is the best way to compare two 2D arrays in JavaScript?

Having an issue comparing two 2D arrays in javascript, looking to output "true" if the arrays are the same. This is the code I experimented with: ` function check(){ if (data.every() === solution.every()){ alert("example"); } else { ...

Simulating a winston logger in jest testing

I am pondering how to create mock transports for the File module within the Winston node package. While utilizing Jest, the __mocks__/winston.ts file is automatically loaded. My dilemma lies in the fact that I am unable to mock it due to the presence of th ...

The promise is unexpectedly fulfilled ahead of schedule without returning the expected value from an AXIOS call

My current challenge involves making a request to a service that rapidly generates multiple strings. The problem lies in returning a promise from this service, as I lack control over the string-generation process. It is crucial for me to return a promise ...

Exploring the latest updates in MUI modern version

The MUI documentation suggests using a modern folder with components designed for modern browsers. Is there a way to configure webpack to automatically rewrite imports like import {Box} from "@mui/material" to use the modern version without manually changi ...

Issue with minifying AngularJS and TypeScript route configuration for safe minification

Currently, I have a package containing multiple js files that were created from typescript files. However, when I attempt to apply minification to the package, the webpage encounters errors. The error message displayed on the Chrome console is: Uncaug ...

Node.js is having trouble locating a module that has been installed

Upon transferring my node.js application to a different PC (where it functioned flawlessly on the development machine) and manually installing all the necessary dependencies, I encountered an error when attempting to run it: C:\Users\myself>n ...

Create an XML document using the DOM structure, but exclude specific elements in the process

Having some HTML that needs to be converted into an XML document, I am struggling to skip certain elements and focus only on the divs. I wrote a simple DOM traversal function to achieve this, but it seems to be stuck in an infinite loop. (More details belo ...

Testing Angular applications using Karma

After utilizing the yo angular 1 generator, it generated a landing page and some tests. However, I am facing an issue when trying to compile the code in VS as I receive an error stating that "module('fountainFooter');" is undefined. /// <refe ...

AngularJS - Filter out items from ng-repeat that match specific string criteria

After successfully cleaning up an external JSON URL feed by removing unnecessary special characters through a filter in my AngularJS code, I am now faced with the challenge of filtering out specific items from an ng-repeat based on a certain string. angul ...

disappearing the link in a window.open popup

I have a situation where I am opening a window with the code window.open("mytest.aspx");. The issue arises when the user closes that pop-up window - I need to have the link on the parent page hidden. In essence, how can I hide the anchor link on the parent ...

What could be causing the partial to not load JavaScript properly?

Hello, I am a newcomer to Angular and I'm currently working on implementing the slick carousel. It functions properly on the index page, but when I try to use the same HTML in a partial and include it with ng-view, it doesn't work as expected. T ...

``If you're looking to retrieve, modify, and display information in your Vue application with the help of

I'm facing an issue where I am trying to retrieve data using the axios get request and then updating it based on the response of another axios get request. However, I am unable to display the data from the second request. The following is a snippet o ...