...

/

Applying States to Single-Page Application (SPA)

Applying States to Single-Page Application (SPA)

Learn how to manage data, handle user interactions, and synchronize views in a single-page application.

Integrating states with a single-page application

We'll start building a single-page application. We'll implement a funtionality to switch to a different page other than the home page. We'll put together a Nav component:

const Nav = ({ items, selected }) => { ... }

Given a list of pages, the Nav component displays them as links to navigate. The currently selected page needs to be provided as well. Now that we know how to define a state, let's use it to keep track of the selected page:

const App = () => {
// Get the currently selected item from the shared state (default: "home")
const selected = _getM("home");
// Render the 'Nav' component with menus, the selected item, and a callback to update the shared state
return (
<div>
<Nav
items={menus}
selected={selected}
onSelect={_setM}
/>
</div>
);
};
React app with navigation menu component and state management

In the App component, we use a state for selected to hold the home key initially, which is then pass into the Nav component. To allow the state to be updated after a user clicks, we need to modify Nav by adding the support of an onSelect callback function:

const Nav = ({ items, selected, onSelect }) => {
// Function to check if a menu item is currently active
const isActive = (item) => item.key === selected;
// Function to handle click events on menu items and update the selected item
const onClick = (item) => () => {
onSelect(item.key);
};
return ();
};
React navigation menu component with item selection

In the amended Nav component, an onSelect prop is passed so that after onClick, the parent App component can be notified to update the selected page via the _setM function.

To confirm that the user does reach a different page, based on the current selected page, we can use a Route component to switch between page content:

const Route = ({ selected }) => {
// Conditionally render content based on the selected item
return (
<div>
{selected === 'home' && <Home />} {/* Render 'Home' component if selected is 'home' */}
{selected === 'product' && <Product />} {/* Render 'Product' component if selected is 'product' */}
</div>
);
};
React Route component for page selection

What the preceding Route component does is display the page ...