When creating an online store, you often have to create whole new pages specific to your store.
Let's look at how it works by adding a "Hello World" page to Front-Commerce Lite.
This page will be accessible at /greetings
and will display Hello World
.
In order to do so, we need to:
- Create our component page in our theme
- Define the associated route in our router
First, let's create a new component in our theme.
This component will be the one telling our application what to display on the /greetings
page.
In order to keep our code clean, we will put this component into the pages
folder of our theme: src/web/theme/pages/<our-page>.js
.
Front-Commerce: If we were to use the paid version, the page should be added at the same path but within a custom module rather than in core modules.
Once created, this component should render a basic "Hello World" message.
// src/web/theme/pages/Greetings.js
import React, { Component } from "react";
import { H1 } from "theme/components/atoms/Typography/Heading";
class Greetings extends Component {
render() {
return <H1>Hello world</H1>;
}
}
export default Greetings;
Once the component is created, we must declare our new route.
A route is a React element that specifies what to display if a specific path is matched.
In our case, we want it to render the Greetings
component when the user visits the /greetings
URL.
To do so, we use React Router, the most popular routing library in the React ecosystem.
In Front-Commerce Lite, routes are gathered in a single file: src/web/theme/Routes.js
.
So, we will add our /greetings
route within this file.
// ... imports
import Route from "react-router/Route";
+import Greetings from "theme/pages/Greetings";
export default () => (
<BrowserRouter>
<Switch>
+ <Route
+ path="/greetings" // The URL that should display our page
+ render={() => <Greetings />} // what page to render
+ />
{/* Other routes here */}
</Switch>
</BrowserRouter>
);
We can now navigate to http://localhost:8080/greetings and it should render your fantastic Hello World
message!
Front-Commerce: If we were to use the paid version, there would be no such root file since routes need to be aggregated from different modules. Read more on Front-Commerce’s documentation
Once you have a custom page up and running, feel free to change the page component (Greetings
) however you want.
You can make it fetch data, render data, send a mutation… after all, it's a component!
It will work exactly the same way as any other component in your application.
We now recommend you to start experimenting with Pages and change things to understand how a page could be organized and reuse existing components!
Then, you could learn how to extend the GraphQL Schema by exposing new information that you may for instance display on this page afterwards.