Exclude page to be wrapped in gatsby wrapPageElement - reactjs

Here's the code in gatsby-ssr and gatsby-browser.
export const wrapPageElement = ({ element, props }) => (
<Store>
<Layout {...props}>{element}</Layout>
</Store>
)
However I want to exclude some pages from being wrapped with Store and Layout, what is the easiest way of doing this?

As it has been said, it's preferable to use wrapRootElelement instead of wrapPageElement for stores or other providers.
That said, you just can:
You can create a new Layout component for those pages/components you don't want to wrap in wrapRootElement.
Use the provided props (location, data, etc) to create a wrapping condition like:
export const wrapRootElement = ({ element, props }) => {
if(props.location.pathname.includes("page-with-wrap"){
return <Store>
<Layout {...props}>{element}</Layout>
</Store>
}
}

Related

Definig page component only by HOC in NextJS

I have nextjs (react) website I use (on every "page") same template - there is Detail and List component.
I have definition of every page as XML (not nextjs thing but my implementation). Root element here is Forms and childrens are individual form defined like this:
<Form FID="Event">
<DetailFrame createNewEntryText="Add event">
<Component attributeKey="img_url" componentName="chose file" componentType="FileChooser" path="img/albums/other/event-photos/#[img_url]"/>
<Component attributeKey="title" componentName="Title" componentType="TextField" transformation="#[title]"/>
<Component attributeKey="date" componentName="Date" componentType="DateField" transformation="#[date]"/>
<Component attributeKey="description" componentName="Description" componentType="RichTextField" transformation="#[description]"/>
</DetailFrame>
<ListFrame orderBy="date" descending="true">
<Component attributeKey="id_event" componentName="ID" componentType="TextField" transformation="#[id_event]"/>
<Component attributeKey="img_url" componentName="Image preview" componentType="ImagePreview" transformation="img/albums/other/event-photos/#[img_url]" />
<Component attributeKey="title" componentName="Title" componentType="TextField" transformation="#[title]"/>
<Component attributeKey="date" componentName="Date" componentType="DateField" transformation="#[date]"/>
<Component attributeKey="description" componentName="Description" componentType="RichTextField" transformation="#[description]"/>
</ListFrame>
</Form>
Only thing what I need specify on every nextjs page is FID and individual component will then compose by their own by XML definition of form. All the stuff like menu and other components (except FormFrameContainer which is wrapper for Detail and List components) are defined in _document.tsx (= html wrapper for nextjs pages offered by nextjs) and _app.tsx (= components wrapper for nextjs pages offered by nextjs; wrapped by _document.tsx). To be clear - FormFrameContainer is wrapped by that stuffs in _app.tsx and _document.tsx.
So every administration page look almost same, like this:
const EventsPage: NextPage = (props: any) =>{
const dispatch = useAppDispatch();
useEffect(() => {
dispatch({ type: SagaActions.SET_FORM_DEFINITIONS_AND_SET_FORM_BY_ID, FID: "Event" });
}, [dispatch])
return (
<div>
<FormFrameContainer />
</div>
)
}
Because of repetition I decided to move useeffect logic into hoc named withAdminPage:
export default (Page: NextPage, formID: string) => {
return (props) => {
const dispatch = useAppDispatch();
useEffect(() => {
dispatch({ type: SagaActions.SET_FORM_DEFINITIONS_AND_SET_FORM_BY_ID, FID: formID });
}, [dispatch])
return <Page {...props} />;
}
}
So literaly the only thing what remains in particular pages is returning:
<div>
<FormFrameContainer />
</div>
What comes to my mind is also move it to hoc, because it is also same in all pages => duplication. But it would mean, that I will not actually define components (my hoc will generate them) and in every page file will be only this one line:
export default withAdminPage(EventsPage, "Event");
For me it seems logic but also as some anitpattern to hoc (because hoc is defined as function, that take component and return new (enhanced) component). So? What would be best practise here? Would it be violation of some code standards?

Problem with wrapping whole React App (all pages) in certain functionality

I have React App consisting of few pages. LandingPage (to be clear, it is really the first page in app flow)is like this:
export const LocalLandingPage = () => {
const { Favorites } = useFavorites();
React.useEffect(() => {
Favorites.manageSupport() && Favorites.showSize();
}, []);
return (...here goes actual content...);
};
const LandingPage = withRouter(wrappedInLinkToSearchHOC(WithSnackBarHOC(LocalLandingPage)));
Here I call hook useFavorites which gathers some methods dealing with a specific subset of local Storage content(and dispatches actions to Redux store as well). The code above return call is checks support for local Storage and tells if some specific items are stored and in what quantity.
The story is that I have realized that if someone enters not the LandingPage but any other page of the app, the code will not be executed and support for localStorage not checked.
Besides, it is really not LandingPage business to deal with storage, so it should be removed anywhere.
My idea was to write HOC and wrap the application. So, here is this HOC (to keep things simple it is initially JS not TS) To make useFavorites work, it had to be a hook, too.
import useFavorites from '../hooks/useFavorites';
const useCheckSupportForLocalStorage = Component => {
const { Favorites } = useFavorites();
// React.useEffect(() => {
Favorites.manageSupport() && Favorites.showSize();
// }, []);
return props => <Component {...props} />;
};
export default useCheckSupportForLocalStorage;
Having it done, I have tried to use it on App like this
function App() {
return (
<Switch>
... here are routes...
</Switch>
);
}
export default useCheckSupportForLocalStorage(App);
It throws an error:
React Hook "useCheckSupportForLocalStorage" cannot be called at the top level.
That is truth, no doubt. So, the next idea was to create a temporary component from all routes.
function Routes() {
const Routes = useCheckSupportForLocalStorage(
<>
<Route exact path={Paths.landing} component={Awaiting(StarWars)} />
...here is the rest or outes...
</>,
);
return <Routes />;
}
export default Routes;
And use it in rewritten App like this
function App() {
return (
<Switch>
<Routes />
</Switch>
);
}
but it throws error
Routes' cannot be used as a JSX component.
Its return type '(props: any) => Element' is not a valid JSX element.
Type '(props: any) => Element' is missing the following properties from type 'ReactElement<any, any>': type, props, key
Forcing useCheckSupportForLocalStorage th have return type of ReactElement doesn't help, just leads to other error. I have checked few others options as well. What is wrong, how should it be written?
Basically I could stop using useFavorites in this hook, then it would be just a function - but it would be extreme headache.
You say
To make useFavorites work, it had to be a hook, too.
That is not true, since you have it in a component it will work just fine. And my understanding is that you want to wrap your whole app with it, so no need for the HOC. Just use it at the top of your app hierarchy.
something like
import useFavorites from '../hooks/useFavorites';
const CheckSupportForLocalStorage = ({ children }) => {
const { Favorites } = useFavorites();
React.useEffect(() => {
Favorites.manageSupport() && Favorites.showSize();
}, []);
return children;
};
export default CheckSupportForLocalStorage;
and
function App() {
return (
<CheckSupportForLocalStorage>
<Switch>
... here are routes...
</Switch>
</CheckSupportForLocalStorage>
);
}
export default App;

Using Persistent Layouts in NextJS with Higher Order Functions

Im using Adam Wathan's method for using persistent layouts in Next. Is there a way to get them to work with Higher Order Functions? I'm not really sure how HOFs work.
My _app.js
function MyApp({ Component, pageProps }) {
const Layout = Component.layout || (children => <>{children}</>)
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
}
A sample page looks like this
const Home = () => {
return (
<>
...
</>
)
}
Home.Layout = BaseLayout;
export const getServerSideProps = withAuthUserTokenSSR()()
export default withAuthUser()(Home)
If I remove the HOF the layouts work fine, otherwise I get:
Error: Objects are not valid as a React child (found: object with keys {children}). If you meant to render a collection of children, use an array instead.
You need to apply the layout component to the higher-order component itself, as it's probably wrapping your original Home component and hiding Home.layout away.
const Home = () => {
return (
<></>
)
}
const HomeWithAuth = withAuthUser()(Home)
HomeWithAuth.layout = BaseLayout;
export default HomeWithAuth
Also, make sure you use the same variable name (same casing, e.g., layout vs. Layout) in your page component and when you refer to it in _app.

Fixed side menu on an specific Next.js route

I'm starting a new project and I would like to always have a top nav and only in a specific route have a sidebar where I can click and the content will change.
The top nav should always be visible if I am in site.com or site.com/*/**
If I go to site.com/posts I want to see a sidebar with all the posts title
If I click a post on the left it will redirect to site.com/posts/1 and only the right side should change
I'm having trouble with the second and third bullet. My pages path is pages/posts/index.js and pages/posts/[id].js but how can I declare only one file and avoid duplicating code? 🤔
I tried pages/posts/[[...slug]].js but I'm seeing this error: Error: Optional catch-all routes are currently experimental and cannot be used by default ("/posts/[[...slug]]")
I'm looking for examples but so far I couldn't do it.
Any ideas?
Update: Next.js now recommends to use function getLayout()
New Documentation ✨
Create a file: /layouts/RequiredLayout.js
const RequiredLayout = ({ children }) => {
return (
<>
<Navbar />
<main>{children}</main>
</>
);
};
export default RequiredLayout;
Then edit _app.js
function MyApp({ Component, pageProps }) {
const Layout = Component.Layout || EmptyLayout;
return (
<Layout>
<Component {...pageProps} />
</Layout>
);
}
const EmptyLayout = ({ children }) => <>{children}</>;
export default MyApp;
Now whenever you require to use this layout, then add only a single line at the end
NameOfComponent.Layout = RequiredLayout;
For in your case: In **pages/posts/[id].js**
import React from 'react'
const ID = () => {
return(
<>
<p>page with id details</p>
</>
)
}
export deafult ID;
ID.Layout = RequiredLayout //responsible for layout
I was able to enable this experimental option by having my next.config.js look like this (I'm using Next v9.4.4):
module.exports = {
experimental: {
optionalCatchAll: true,
},
};

How do I combine ramda with recompose?

I have this component;
const ReposGrid = R.pipe(
R.prop("repos"),
// branch(R.isEmpty, renderComponent(Loader)),
R.map(Repo),
ReposWraper
)
export default ReposGrid
This works fine but I want to render loader component if repos is empty. My branch from recompose just doesn't do anything. It doesn't show Loader neither displays repos when it's loaded. Can I apply R.ifElse here?
You might be mixing up ramda's pipe/compose and recompose's, and the arguments they take. Your chain is made up of a mix of higher order components and functions operating on props. It's best to keep the data handling in mapProps/withProps etc.
You might be able to achieve something similar to what you're after like this:
import { map, evolve, propSatisfies, isEmpty } from 'ramda'
import { compose, branch, renderComponent, mapProps, renameProp } from 'recompose'
const Repo = (repo) => <div>Repo {repo}</div>
const Loader = () => <div>Loader</div>
const RepoGridBase = props => <div>{props.children}</div>
const ReposGrid = compose(
branch(
propSatisfies(isEmpty, 'repos'),
renderComponent(Loader),
),
mapProps(evolve({
repos: map(Repo)
})),
renameProp('repos', 'children')
)(RepoGridBase)
function App() {
return (
<div className="App">
<ReposGrid repos={[]} />
<ReposGrid repos={['one', 'two']} />
</div>
);
}
(this will throw key warnings, you'd probably be better of doing the map inside of a component explicitly)
codesandbox link

Resources