reactjsmeteorserver-side-rendering

React Router: Accessing Params in the Server for SSR


I've just started to play around with this package that makes it super easy to integrate SSR.

https://github.com/Meteor-Community-Packages/react-router-ssr

The thing is I do not know how to access the route/query params or such url data from within the server component, and therefore I can't render a specific content. So for the code below, I don't know how I could inject the documentId into the Sample server component. It is probably a specific react-router syntax injecting as a prop...?

TLDR: Since I can't use hooks hence the builtin useParams hook, how do I get access to the param in the server component?

Thanks!

function Sample(props) {
    Meteor.subscribe('document', 'documentId');
    const document = Documents.findOne();
    return <h1>{document.title}</h1>
}

const AppRoutesSSR = [{
    path: '/documents/:documentId'.
    element: <Sample documentId='???documentId???' />
}, {
    ...
}]

renderWithSSR(AppRoutesSSR, {
  renderTarget: 'root',
});

Solution

  • Indeed it is apparently possible to use hooks, specifically the useParams hook from react router itself.

    So:

    import { useParams } from 'react-router-dom'
    
    function Sample() {
        const { documentId } = useParams();
        Meteor.subscribe('document', documentId);
        const document = Documents.findOne(documentId);
        return <h1>{document.title}</h1>
    }
    

    Bamm!