Search code examples
typescriptpreactpreact-router

Preact router Property 'path' does not exist on type 'IntrinsicAttributes'


I am currently going through a problem whilst making a website of mine with preact router. whenever I try to put something in the router it has an error of Property 'path' does not exist on type 'IntrinsicAttributes'. But it doesn't stop the site from running but whenever I change the url to '/shop' it doesn't show anything. shop function

import { Item } from '../../Types/types'
import './item.css'
import Navbar from '../Navbar'
export default function Items(items:Array<Item>) {
    return (
    <>
    <Navbar />
    <div className='container'>
    {
    items.map( item => { 
    return ( 
    <div className='item'>
        <div>
            <h3>
                {item.name}
            </h3>
        </div>      
        <div className='itemimage'>
            <img src={item.picture} alt={item.name} />
        </div>
        <div>
            <strong>{item.price}</strong>
        </div>
    </div>
    )})
    }
    </div>
    </>
    )
}

and my router function

import Router from 'preact-router'
import {App} from '../app'
import Items from './shop/items'
export const Route = () => {
    return (
    <Router>
    <App path='/' />
    <Items path='/shop' />  
    </Router>
    )
}

I tried following the tutorial on preact router. It did not work. I then tried to look up this problem there was nothing about this exact problem with preact-router.


Solution

  • This is an inherent limitation of TS, though there is an alternative which is the <Route> component, exported from preact-router:

    import { Route, Router } from 'preact-router'
    import { App } from '../app'
    import Items from './shop/items'
    
    export const RouteX = () => {
        return (
            <Router>
                <Route path="/" component={<App />} />
                <Route path="/shop" component={<Items />} />
            </Router>
        )
    }
    

    Essentially, the strictness of TS means that <Router> can't define its children as additionally taking a path prop. So instead of applying your path to the component directly, you will need to use a wrapper to appease TS.

    But it doesn't stop the site from running but whenever I change the url to '/shop' it doesn't show anything

    It doesn't show anything as you're a) not using props correctly and b) not passing items to <Items>.

    export default function Items({ items: Array<Item> }) {
    
    <Route path="/shop" component={<Items items={...} />} />
    

    Props are always an object, so you'll need to destructure or access .items on your props object. As you're not providing items to <Items> though, your component has no data to work with.