[Preact] Integrate react-router with Preact
React-router is the community favourite routing solution - it can handle all of your complex routing needs and in this lesson we’ll cover what’s needed to enable it’s use within Preact. https://github.com/ReactTraining/react-router
in webpack.config.js:
resolve: { alias: { 'react': 'preact-compat', 'react-deom': 'preact-compat' } },
Add resolve block. it alias 'react' to use 'preact-compat'.
Change Route definations.
import {h} from 'preact'; import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import Profile from './Profile'; import Home from './Home'; import Error from './Error'; export default function App() { return ( <Router> <Switch> <Route path='/' component={Home} exact /> <Route path='/profile/:user' component={Profile} /> <Route component={Error}></Route> </Switch> </Router> ); }
Using 'Switch' to allow only one component showing at a time.
Dealing with navigation:
import { h } from 'preact'; import {withRouter} from 'react-router-dom'; function search(router, query) { router.history.push(`/profile/${encodeURIComponent(query)}`); } const Home = withRouter((router) => { return ( <section> <p>Enter a Github Username</p> <input type="search" placeholder="username" onSearch={e => search(router, e.target.value)} /> </section> ); }); export default Home;
We can use High Order component 'withRouter', it inject 'router' param into our component, then we can use:
router.history.push(`/profile/${encodeURIComponent(query)}`);
to nav around.
Get router params:
componentDidMount() { const username = this.props.match.params.user; fetch(`${config.url}/${username}`) .then(resp => resp.json()) .then(user => { this.setState({ user, loading: false }); }) .catch(err => console.error(err)); }
You can get the router param by using:
const username = this.props.match.params.user;
Link tag:
import {h} from 'preact'; import {Link} from 'react-router-dom'; export default Error = () => ( <div> <h2>Error!</h2> <Link to='/'>Home</Link> </div> );
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2013-06-20 【大型网站架构 原理】1. 负载均衡和冗余技术