javascripttypescriptjsxsolid-js

Pass component and add style to it with solidjs and TypeScript


I have several icons in my web application which look like this:

type IconProps = ComponentProps<"svg">

const Icon = (props: IconProps) => {
  const [, rest] = splitProps(props, ["class"])
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
      class={cn("", props.class)}
      {...rest}
    />
  )
}

export function IconUser(props: IconProps) {
  return (
    <Icon {...props}>
      <path .... />
    </Icon>
  )
}

Next I want to write the following component to receive one of the various icons and render it. However I need the ability to add the style prop to the given icon.

export const SettingButton = (props: {
    title: string;
    icon: ?; // JSX.Element maybe? 
    onPress: () => void;
}) => {
const { hovering, hoveringProps } = useHovering();
const responsive = useResponsiveV2();
const color = () => {
    if (hovering()) {
        return c.colors.text.secondary;
    }
    return c.colors.text.tertiary;
};

return (
    ? // {props.icon} works but I want to add the style prop to it here
// Ideally {props.icon style={{color: color()}}}
)}

// Usage: <SettingButton title={"Test"} icon={<IconUser />} onPress={() => {}} />

Please note that I am using solidjs so to my knowledge cloneElement is not available.

Also I know I could wrap this in a div and apply the style there but I am wondering how to do it right.


Solution

  • I have honestly no idea about SolidJS, but I came up with a quick code (by playing around in Codesandbox) that might do the work for you:

    const SettingButton = (props) => {
      const Icon = props.icon;
      return (<Icon style={{ color: "red" }} />)
    }
    
    function IconUser(props) {
      return <h1 style={props.style}>Test</h1>
    }
    
    function App() {
     return ( <SettingButton icon={IconUser} /> );
    }