Adding Pages
Overview
When adding a new page please consider whether the functionality can be included in an existing page first.
Adding a new page requires a few steps:
- Create a new functional component in
src/renderer/components/pageswhich will render the page. Start with the most basic component first. (e.gCoolCatPage.tsx) - Add a Path value to
src/renderer/Paths.ts(e.gCATS = '/cats') - Add a Route with this new Path value in
src/renderer/router.tsx- Searching for
<PropsRouteis a really easy way to find the right place
- Searching for
- Create an instance of the Props type your components needs immediately above this in
src/renderer/router.tsxand pass it to thePropsRouteyou created.- You may need to pass additional data from the top level
app.tsxcomponent. Do this by adding the values toAppRouterPropsfirst, then searching forconst routerProps: AppRouterProps = {and adding them inapp.tsx
- You may need to pass additional data from the top level
Practical Example
- Create a new functional component in
src/renderer/components/pageswhich will render the page. Start with the most basic component first.
src/renderer/pages/CoolCatPage.tsx
export type CoolCatPageProps = {
platformNames: string[];
}
export function CoolCatPage(props: CoolCatPageProps) {
// Pick a random platform name to use
const platformIdx = Math.floor(Math.random() * props.platformNames.length);
const platform = props.platformNames[platformIdx];
// Show `I'm a Flash cat!` or something equivalent on screen
return (
<div>
{`I'm a ${platform} cat!`}
</div>
)
}
- Add a Path value to
src/renderer/Paths.ts(e.gCATS = '/cats')
src/renderer/Paths.ts
export enum Paths = {
// ...
CATS = '/cats'
}
- Add a Route with this new Path value in
src/renderer/router.tsx, create an instance of the Props type your components needs immediately above this insrc/renderer/router.tsxand pass it to thePropsRouteyou created.
src/renderer/router.tsx
export type AppRouterProps = {
// ...
platforms: string[]; // This already exists, following the example we'll assume it doesn't
}
export class AppRouter extends React.Component<AppRouterProps> {
render() {
// ...
const coolCatProps: CoolCatPageProps = {
platformNames: this.props.platforms, // platforms is already here, so we can use that
}
// ...
return (
<Switch>
{ /* ... */ }
<PropsRoute
path={Paths.CATS}
component={CoolCatPage}
{ ...coolCatProps }
/>
<Route component={NotFoundPage} />
</Switch>
);
}
}
- If you don't have access to the data required for your component props, then add them to the Router props and send them from
app.tsx.
Alternatively you may consider not having them as props, but fetching them only once via a backend request when the component mounts. (See React's useState and useEffect hooks)
Assuming the data exists in the scope of App, we can get it from the main state.
src/renderer/app.tsx
render() {
// ...
const routerProps: AppRouterProps = {
// ...
platforms: this.props.main.platforms // Assuming this exists on the main state
}
}