### Installing and Configuring Crossroad in React Source: https://github.com/franciscop/crossroad/blob/master/readme.md This section covers the installation of the Crossroad library using npm and provides a minimal example of how to import and use its core components, Router, Switch, and Route, to define simple routes for a React application. ```javascript npm i crossroad ``` ```javascript import Router, { Switch, Route } from "crossroad"; export default function App() { return ( ); } ``` -------------------------------- ### Query Parameter Matching Examples Source: https://github.com/franciscop/crossroad/blob/master/readme.md Demonstrates how the Route component can match based on the presence and values of query parameters in the URL. It includes examples of matching specific query keys and values, as well as wildcard usage with query parameters. ```javascript // In /profile?page=settings&filter=abc // All of these match the current route // These shall not match: // Wrong path // Wrong key // Wrong value ``` -------------------------------- ### React Router Import Examples (for comparison) Source: https://github.com/franciscop/crossroad/blob/master/readme.md These examples demonstrate various ways to import components from 'react-router' and 'react-router-dom'. The documentation uses these to illustrate the complexity and potential confusion in React Router's import statements. ```javascript import { Switch, Route, ... } from 'react-router'; import Router from 'react-router-dom'; import Router, { Switch, Route, ... } from 'react-router-dom'; import { Switch, Route, ... } from 'react-router'; import { BrowserRouter } from 'react-router-dom'; ``` -------------------------------- ### Crossroad Import Example Source: https://github.com/franciscop/crossroad/blob/master/readme.md This code snippet shows the recommended way to import components from the 'crossroad' library. It highlights a more intuitive and concise import syntax compared to React Router. ```javascript import Router, { Switch, Route, ... } from 'crossroad'; ``` -------------------------------- ### Link Behavior Examples with Crossroad Source: https://github.com/franciscop/crossroad/blob/master/readme.md Provides various examples of anchor tag usage with Crossroad, illustrating different navigation behaviors such as in-app navigation, external links, and targeted tab opening (`_self`, `_blank`). ```jsx // In https://example.com/users/25 // React navigation: Home // React navigation: New users // Page refresh (since it's a full URL) Google it // Page refresh (a full URL, even in the same domain) Home // Page refresh (it has a target="_self") Update // New tab (it has a target="_blank") Read terms of service ``` -------------------------------- ### Crossroad Router Basic App Example (JavaScript) Source: https://github.com/franciscop/crossroad/blob/master/readme.md A simple React application example using the Crossroad routing library. It defines routes for Home, Users, and a NotFound component, showcasing how to pass a 'url' prop to the Router for testing purposes. ```javascript // App.js import Router, { Switch, Route } from "crossroad"; // Imagine these are your apps and components: const Home = () =>
Home
; const Users = () =>
Users
; const NotFound = () =>
Website not found
; export default function App({ url }) { return ( ); } ``` -------------------------------- ### Adding Navigation Links and Route Components in Crossroad Source: https://github.com/franciscop/crossroad/blob/master/readme.md This example illustrates how to integrate navigation links with anchor tags and define specific page components for different routes using Crossroad's Route component. It shows a more complete setup with home and user profile routes. ```javascript import Router, { Switch, Route } from "crossroad"; const Home = () =>
Home Page
; const Profile = ({ id }) =>
Hello {id.toUpperCase()}
; export default function App() { return ( ); } ``` -------------------------------- ### Basic React Router Setup with Crossroad Source: https://github.com/franciscop/crossroad/blob/master/assets/home.html This snippet demonstrates the fundamental setup of the Crossroad router. It utilizes Switch and Route components to define navigation paths and associate them with specific components. The main Router component wraps the entire routing structure. ```javascript import Router, { Switch, Route } from "crossroad"; export default () => ( ); ``` -------------------------------- ### Link Navigation in React Router (for comparison) Source: https://github.com/franciscop/crossroad/blob/master/readme.md Shows examples of how links are handled in React Router, highlighting the inconsistencies that Crossroad aims to resolve. This includes using both `` and `` components for different navigation scenarios. ```html // React Router // Normal link Hello // Open in same page with refresh Hello Hello // Open in new page Hello Hello // Broken ``` -------------------------------- ### Router Component Setup with Navigation Source: https://context7.com/franciscop/crossroad/llms.txt The Router component wraps the application, managing navigation state and history. It intercepts click events on anchor tags for internal routing. This example demonstrates basic navigation to Home, Users, and a specific User Profile. ```javascript import Router, { Switch, Route } from "crossroad"; const Home = () =>
Welcome Home
; const Users = () =>
User List
; const Profile = ({ id }) =>
User Profile: {id}
; export default function App() { return (
); } ``` -------------------------------- ### Crossroad App: Routing and Navigation Example (JavaScript/React) Source: https://context7.com/franciscop/crossroad/llms.txt This JavaScript code defines a complete React application using the Crossroad routing library. It demonstrates setting up routes for home, search with query parameters, category listings with dynamic segments, item details, and a 404 fallback. It utilizes Crossroad's `Router`, `Switch`, `Route`, `useQuery`, `useParams`, and `usePath` hooks for declarative and programmatic navigation. ```javascript import Router, { Switch, Route, useQuery, useParams, usePath } from "crossroad"; import { useState, useEffect } from "react"; // Home page component const Home = () => (

Welcome to Our App

Navigate using the menu above

); // Search page with query parameters const Search = () => { const [query, setQuery] = useQuery(); const [results, setResults] = useState([]); useEffect(() => { if (query.q) { // Simulate API call setResults([ { id: 1, title: `Result for: ${query.q}` }, { id: 2, title: `Another match for: ${query.q}` } ]); } }, [query.q]); const handleSearch = (e) => { e.preventDefault(); setQuery({ q: e.target.search.value }); }; return (
{results.map(r => ( ))}
); }; // Category listing with pagination const Category = ({ category, page }) => { const items = [`${category}-item-${page}-1`, `${category}-item-${page}-2`]; return (

{category} - Page {page}

    {items.map(item =>
  • {item}
  • )}
); }; // Item detail page const ItemDetail = ({ id }) => { const [path, setPath] = usePath(); const goBack = () => { setPath("/search"); }; return (

Item #{id}

Details for item {id}

); }; // 404 Not Found const NotFound = () => (

404 - Page Not Found

Go Home
); // Main App export default function App() { return (
); } ``` -------------------------------- ### Route Matching Examples with Path and Wildcard Source: https://github.com/franciscop/crossroad/blob/master/readme.md Demonstrates how the Route component matches different URL paths, including exact matches, partial matches using wildcards, and parameter-based routing. It shows when a component is rendered based on the current URL. ```javascript /* In https://example.com/ */ // Rendered // Rendered // Not rendered // Not rendered /* In https://example.com/user/ */ // Not Rendered // Rendered // Rendered // Rendered ``` -------------------------------- ### Wildcard Path Matching Examples Source: https://github.com/franciscop/crossroad/blob/master/readme.md Shows various scenarios where a wildcard '*' at the end of a path prop enables partial route matching. This allows a route to match a segment of the URL, similar to a 'catch-all' route. ```javascript // In https://example.com/user/abc // All of these match the current route ``` -------------------------------- ### Basic React App Navigation Setup with Crossroad Source: https://github.com/franciscop/crossroad/blob/master/readme.md This snippet demonstrates the fundamental structure for setting up navigation in a React application using Crossroad. It involves importing the Router, Switch, and Route components and defining basic navigation links using anchor tags. ```javascript import Router, { Switch, Route } from "crossroad"; export default function App() { return ( ); } ``` -------------------------------- ### Basic Router Setup Source: https://github.com/franciscop/crossroad/blob/master/readme.md The top-level Router component must wrap all other components to manage clicks and history. It's the default export of the library and should be integrated within your main App component. ```javascript import Router from "crossroad"; export default function App() { return ... Your normal App code ...; } ``` -------------------------------- ### Router with Nested Routes and Switch Source: https://github.com/franciscop/crossroad/blob/master/readme.md This example demonstrates a common setup where the Router component wraps a Switch component, which in turn contains multiple Route components. This pattern is used to define different pages or views for specific URL paths in a React application. ```javascript import Router, { Switch, Route } from "crossroad"; import Home from "./pages/Home"; import Dashboard from "./pages/Dashboard"; import Profile from "./pages/Profile"; export default function App() { return ( ); } ``` -------------------------------- ### Express Server-Side Rendering with Crossroad Source: https://github.com/franciscop/crossroad/blob/master/readme.md This example illustrates how to integrate Crossroad for server-side rendering within an Express application. It shows how to render a React component (`App`) with a specified URL, enabling dynamic routing on the server. This is useful for pages like '/users' and '/users/:id'. ```javascript // An express example const App = ({ url }) => ...; app.get("/users", (req, res) => { res.render(); }); app.get("/users/:id", (req, res) => { // {...} validate the `id` it here! res.render(); }); ``` -------------------------------- ### Updating URL with `useUrl` Setter Source: https://github.com/franciscop/crossroad/blob/master/readme.md Provides examples of how to use the `setUrl` function returned by the `useUrl` hook to navigate to new paths, modify query parameters, and add hashtags. Supports string or object-based updates. ```javascript const [url, setUrl] = useUrl(); // [Shorthand] Redirect to home with a hashtag setUrl("/#firsttime"); // Same as above, but specifying the parts setUrl({ path: "/", hash: "firsttime" }); // Keep everything the same except the path setUrl({ ...url, path: "/" }); // Set a full search query setUrl({ ...url, query: { search: "hello" } }); // Modify only one query param setUrl({ ...url, query: { ...url.query, safe: "no" } }); ``` -------------------------------- ### Switch with Route Prioritization and 404 Handling Source: https://github.com/franciscop/crossroad/blob/master/readme.md The Switch component renders only the first matching Route. This example shows how to handle specific routes before a more general one (like '/:username') and how to define a fallback route for unmatched URLs using a component without a path attribute. ```javascript // In https://example.com/help, it'll render the Help component only ``` ```javascript ``` -------------------------------- ### Query Routing for Subpages and Tabs in React (JS) Source: https://github.com/franciscop/crossroad/blob/master/readme.md Shows how to define the current page using query parameters instead of the pathname, suitable for subpages or tabs. It includes examples for redirecting to a default home page if no match is found and for handling specific tabs within a dashboard. ```js ``` ```js ``` -------------------------------- ### Type Conversion for Route Parameters Source: https://github.com/franciscop/crossroad/blob/master/readme.md Illustrates the Route component's ability to attempt type conversion for matched path parameters. It shows examples of converting to 'number' and 'date' types, noting that it does not perform validation. ```javascript { console.log(id, typeof id); // 25 number }} />; { console.log(time, typeof time); // Jan 25th, 2055 Date }} />; ``` -------------------------------- ### Accessing URL Parts with `useUrl` Source: https://github.com/franciscop/crossroad/blob/master/readme.md Illustrates how to access the different components of the URL (path, query, hash) provided by the `useUrl` hook. It also explains memoization for performance. ```javascript // In /whatever?filter=hello#world const [url, setUrl] = useUrl(); console.log(url.path); // /whatever console.log(url.query); // { filter: hello } console.log(url.hash); // world ``` -------------------------------- ### Define Static Routes with Crossroad Router Source: https://github.com/franciscop/crossroad/blob/master/readme.md Sets up static routes for a company website, mapping URL paths to corresponding React components. It uses the `Router`, `Switch`, and `Route` components from the 'crossroad' library. Navigation is handled via standard `` tags. ```javascript import Router, { Switch, Route } from "crossroad"; import Nav from "./Nav"; import Pages from "./Pages"; export default function App() { return (