Unleashing the Power of Typescript and SolidJS: Expanding the Properties of JSX Elements

Is there a way to enhance the props of an existing JSX element in SolidJS and craft a custom interface similar to the ButtonProps interface shown in this React example below?

import Solid from 'solid-js';

interface ButtonProps extends Solid.ButtonHTMLAttributes<HTMLButtonElement> {
  title: string;
  showIcon: boolean;
}

const Button: Solid.FC<ButtonProps> = ({ title, showIcon, ...props }) => {
  return (
    <button {...props}>
      {title}
      {showIcon && <Icon/>}
    </button>
  );
};

Answer №1

This has been my go-to approach:

import type { Component, JSX } from "solid-js";
import { splitProps } from "solid-js";

export type ButtonProps = {
  title: string;
  showIcon: boolean;
} & JSX.HTMLAttributes<HTMLButtonElement>;

const Button: Component<ButtonProps> = (props) => {
  const [, rest] = splitProps(props, ["title", "showIcon"]);
  return (
    <button {...rest}>
      {props.title}
      {props.showIcon && <Icon/>}
    </button>
  );
}

In the example above, I utilized a type intersection, but an alternative method could involve extending the interface.

Within this code snippet, I've made use of the Component type, which currently includes an optional children prop in the props. However, this is slated to change with the upcoming 1.4 release.

Furthermore, I've incorporated the splitProps function to prevent destructuring and maintain reactive updates to the prop values.

Answer №2

Similarly, the method to achieve this is quite comparable, with the exception of refraining from destructuring for reactive properties and using splitProps instead. For instance, your code snippet would now look like:

import { splitProps, JSX } from 'solid-js';

interface ButtonProps extends JSX.ButtonHTMLAttributes<HTMLButtonElement> {
  title: string;
  showIcon?: boolean; 
}

const Button = (props: ButtonProps) => {
  const [local, buttonProps] = splitProps(props, ['title', 'showIcon']);
  return (
    <button {...buttonProps}>
      {local.title}
      {local.showIcon && <Icon/>}
    </button>
  );
};

It's worth noting that the attributes' types for intrinsic elements are within the realm of JSX in solid, courtesy of jsx-dom-expressions responsible for converting JSX into reactive expressions.

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

Error: Typings: Invalid syntax - Unexpected symbol =>

Every time I run a typings command, I encounter the following error: AppData\Roaming\npm\node_modules\typings\node_modules\strip-bom\index.js:2 module.exports = x => { ^^ SyntaxError: Unexpected tok ...

Error: Unable to locate bundle.js when attempting to refresh the page with a specific ID in the URL

I encountered an issue where I tried redirecting a user to their profile page to display the profile information corresponding to it. Let's say we have http://localhost:8080/user/1 as an example. Upon redirecting the user using the navbar link, the pa ...

leveraging the import statement in conjunction with SystemJs

Currently, I am in the process of creating a sample code using TypeScript and SystemJS for the browser. In my app.ts file: import {Person,add as test} from './testLib' In the generated app.js file (by TypeScript compiler): var testLib_1 = re ...

One important rule to remember when using React Hooks is that they must be called consistently and in the correct order in each render of the component. It

Encountering an issue while trying to use the ternary operator to determine which React Hook to utilize. The error message states: "React Hook "useIsolationDynamicPhase" is called conditionally. React Hooks must be invoked in the same order during every co ...

Exploration of mapping in Angular using the HttpClient's post

After much consideration, I decided to update some outdated Angular Http code to use HttpClient. The app used to rely on Promise-based code, which has now been mostly removed. Here's a snippet of my old Promise function: public getUser(profileId: nu ...

What is the best way to call a method from app.component in another component?

Having recently delved into Typescript and Angular 2, I've been struggling to find a solution online that fits my needs. Let's consider the example of an app.component: export class AppComponent implements OnInit { constructor(public _test ...

Utilizing Google Sheets as a secure, read-only database for Angular applications without the need to make the sheet accessible to the

Seeking a way to utilize Google Sheets document as a read-only database for my Angular application, I have attempted various methods. However, the challenge with all these approaches is that they necessitate public sharing of the Sheet (accessible to anyon ...

Personalized path-finding tree iterator

I am trying to implement a custom iterator in JavaScript that can traverse a DOM tree based on specific criteria provided by a callback function. The goal is to return an array of the nodes that match the criteria as the generator iterates through the tree ...

Utilizing variables to set the templateUrl in Angular2

Trying to assign a variable to the templateUrl in my component, but it's not functioning as expected. @Component({ selector: 'article', templateUrl: '{{article.html}}', styleUrls: ['styles/stylesheets/article.comp ...

The issue of resolving NestJs ParseEnumPipe

I'm currently using the NestJs framework (which I absolutely adore) and I need to validate incoming data against an Enum in Typscript. Here's what I have: enum ProductAction { PURCHASE = 'PURCHASE', } @Patch('products/:uuid&apos ...

I'm curious about the significance of this in Angular. Can you clarify what type of data this is referring

Can anyone explain the meaning of this specific type declaration? type newtype = (state: EntityState<IEntities>) => IEntities[]; ...

What could be the reason behind TypeScript ignoring a variable's data type?

After declaring a typed variable to hold data fetched from a service, I encountered an issue where the returned data did not match the specified type of the variable. Surprisingly, the variable still accepted the mismatched data. My code snippet is as fol ...

Transform Loopback 4 filter into a SQL WHERE condition

When using Loopback 4, the filter object that is received by functions like Get and Count appears as shown below: { where: { property: { op: value; } } } I am interested in converting this structure into an SQL WHERE clause to use it in ...

Display a loading indicator with the shortest possible delay whenever utilizing the React Router v6 Link functionality

Integrate React and Router v6 App.tsx: const Page1 = lazy(() => pMinDelay(import('./views/Page1'), 500)) const Page2 = lazy(() => pMinDelay(import('./views/Page2'), 500)) return ( <Suspense fallback={<Loading/>}gt ...

Struggling with setting up eslint in my typescript project

Below is the contents of my package.json file: { "devDependencies": { "@typescript-eslint/eslint-plugin": "^5.13.0", "@typescript-eslint/parser": "^5.13.0", "airbnb": "^0.0.2&qu ...

What could be causing this TypeScript class to not perform as anticipated?

My goal with this code snippet is to achieve the following: Retrieve a template using $.get(...), Attach an event listener to the input element within the template I am using webpack to transpile the code without encountering any issues. The actual cod ...

What is my strategy for testing a middleware that accepts arguments?

Here is the middleware I am working with: function verifyKeys(expectedKeys: string[], req: Request): boolean{ if (expectedKeys.length !== Object.keys(req.body).length) return false; for (const key of expectedKeys) { if (!(key in req.body)) return ...

What's the trick to aligning the label on the material-ui text field to the right side?

I am working on a React project with an RTL layout using material-ui and typescript. I am struggling to align the label of a text field to the right. Can anyone help me with this? ...

In TypeScript, leveraging the spread operator to determine the largest value in an array containing nullable numbers

Having an array of nullable numbers presented in the following way: let myArray : Array<number | null> = [1,2,null,4,null,5]; let maximumOfMyArray = Math.max(...myArray); // Type null is not assignable to type number I am content with JavaScript tre ...

What sets apart Resumability, Hydration, and Reconciliation in today's web applications?

Can you explain the key distinctions among Resumability, Hydration, and Reconciliation? As Resumability is considered the future of web apps, is it feasible to make current met frameworks such as Nextjs, Remix, Sveltekit, Solidstart, etc., resumable? ...