nextjs-headless-wp

Nextjs, Headless WordPress, TypeScript, GraphQL, TailwindCSS (by DopamineDriven)

Nextjs-headless-wp Alternatives

Similar projects and alternatives to nextjs-headless-wp

NOTE: The number of mentions on this list indicates mentions on common posts plus user suggested alternatives. Hence, a higher number means a better nextjs-headless-wp alternative or higher similarity.

nextjs-headless-wp reviews and mentions

Posts with mentions or reviews of nextjs-headless-wp. We have used some of these posts to build our list of alternatives and similar projects. The last one was on 2022-03-24.
  • Unwrapping Reacts Core; access JSX.IntrinsicElement props globally (no imports required)
    2 projects | dev.to | 24 Mar 2022
    While working with forms in a current Next + Headless WordPress build I found myself wanting to access, for example, the props of an or a or an and so on and so forth using as little effort as possible. This resulted in many trial and error attempts at piecing together an intuitive, comprehensive, globally consumable solution (intellisense from the current working versions use with -- pictured below): That said, and as one might expect, there were a number of partial-solutions preceding the current singular "one-size-fits-all" solution. Defining an Objective The ideal solution in my mind was two-fold: (1) global re-usability, project-agnostic, adhere to native (React namespace) type definition usage; (2) piece something together that even the most "cowabunga" of js-only developers could get behind -- without compromising on type safety at any time. Phase One -- Generics = <3 If your aim involves tackling bigger picture, project-wide, type-related goals then generics are likely already an integral part of your arsenal. However, if you haven't worked with generics before then you're in luck! The remainder of this post deals with types that heavily rely on generic properties. You could say it's a typeof acquired taste, one that grows on you from the moment your first generic expression "clicks". Generics -- a brief Primer If you're already familiar with using generics feel free to skip ahead to the next section. If not, let's dive right in! A Simple Generic Starter - Unwrapping a Promise // disambiguation: see line 1482 of node_modules/typescript/lib/lib.es5.d.ts for info on Promise vs PromiseLike export type UnwrapPromise = T extends | PromiseLike | Promise ? U : T; Enter fullscreen mode Exit fullscreen mode You might be asking yourself something along the lines of "When the hell exactly is this type useful? How is it useful? Why is it useful? In What contexts is it most useful?" which are great questions to consider. Scrutiny is a beautiful thing. To address these hypothetical questions which you may or may not be asking yourself, the UnwrapPromise type is exceedingly useful when it comes to inferring the return type of an async function (a promise) Think of seeding files that return data with a whole lot going on in the context of types -- often manifesting as a single 1,000+ line async function in practice. Sounds like a royal pain in the ass to statically type out, right? Right. It absolutely would be -- but it can be tackled in a couple lines of clean generic-laced code -- let's approach this using our simple generic from above as the cornerstone (code snippets from another recent project linked here & within this paragraph above): export async function seed( prisma: T ) { // line 5 -- lots of data mimicry unfolds below // ... // line 1067 -- the main event const seedUser = async () => { return await prisma.user.create({ data: { // schema.prisma models/types seeded here }, include: { sessions: true, accounts: true, profile: true, entries: true, _count: true, comments: true } }); }; return seedUser(); } // line 1,193 -- let's unwrap this sizeable beast // similar to the type we defined previously type UnwrapPromise = T extends Promise ? U : T; // use built-in ReturnType inside of UnwrapPromise type SeedInferred = UnwrapPromise>; // enhance precision by extending Record type SeedPropsInferred = UnwrapPromise< typeof seed extends Record ? Record : UnwrapPromise >; Enter fullscreen mode Exit fullscreen mode Two of the three generics that we just defined are integral parts of the main function below. The latter function calls on the lengthy seed function when a yarn seed script is executed in the terminal. This prompts the seed function to trigger, generating quasi-random data for a new user which is ultimately persisted by MongoDB Atlas for the particular repo in question. At any rate, let's see how the return type of seed is inferred in main async function main() { const prisma = await import("../server/Context/prisma"); try { await prisma.default .$connect() .then(() => console.log("[seeding]: db connection opened")); const s: SeedPropsInferred<{ props: typeof prisma; }> = async (): Promise => await seed(prisma.default).then(data => { console.log( JSON.stringify( `[seeding]: success 🎉 created ${data.role} with id ${data.id} and email ${data.email}`, null, 2 ) ); return data; }); return await s(prisma.default); } catch (err) { console.error(err); process.exitCode = 1; } finally { return await prisma.default .$disconnect() .then(() => console.log(`[seeding]: db connection closed`)); } } main(); Enter fullscreen mode Exit fullscreen mode The following snippet is arguably the most important to grapple with in the context of understanding type inference: const s: SeedPropsInferred<{ props: typeof prisma; }> = async (): Promise => await seed(prisma.default).then(data => { console.log( JSON.stringify( `[seeding]: success 🎉 created ${data.role} with id ${data.id} and email ${data.email}`, null, 2 ) ); return data; }); return await s(prisma.default); Enter fullscreen mode Exit fullscreen mode Why? Well, we know that the seed function takes prisma: PrismaClient as a prop, so it's only its return type(s) that would otherwise be a mystery. That, and it would be reasonable to assume that the success value returned by the main instantiating function mirrors that of the value returned by the seed function (it does). With the above logic in place intellisense doesn't miss a beat and perfectly infers the shape(s) of the returned data. Nice. Now, back to React+JSX for the remainder of the article → Phase Two: Unwrapping a single JSX.IntrinsicElement First, let's find the type definition for an JSX.IntrinsicElement: declare global { namespace JSX { // some interesting generic usage happening here interface IntrinsicElements { // other elements input: React.DetailedHTMLProps, HTMLInputElement>; // more elements } } } Enter fullscreen mode Exit fullscreen mode declare global { namespace JSX {} } was intentionally included in the above typedefinition as it's important to think about where types are coming from, where they could go, and how we could use generics to achieve various desired outcomes. The first method I used when approaching this task was a localized, cut'n'dry, mimicry + mapping approach: export type UnwrapInputProps< T extends keyof DetailedHTMLProps< InputHTMLAttributes, HTMLInputElement > > = { [P in T]?: DetailedHTMLProps< InputHTMLAttributes, HTMLInputElement >[P]; }; Enter fullscreen mode Exit fullscreen mode In the above UnwrapInputProps type definition, T is extending the keyof an exact replica of the inner workings of the official input JSX.IntrinsicElement typedef we looked up at the start of this phase. UnwrapInputProps is used for scaffolding custom input components in practice as follows: export const InjectNameInput = ({ ...props }: UnwrapInputProps< | "className" | "type" | "name" | "autoComplete" | "id" | "required" | "value" | "onChange" | "placeholder" >) => ; Enter fullscreen mode Exit fullscreen mode Upon examining the intellisense it quickly becomes clear that... ...this is hardly an optimized or ideal approach as far as widespread adoption is concerned. Why? It necessitates the manual entering of each desired prop-type which can be annoying to remember and tedious to maintain, especially with multiple devs in a single codebase. Let's see how InjectNameInput is actually consumed Enter fullscreen mode Exit fullscreen mode Next, our final phase, phase tres. While there are other interesting intermediates on the way to the current working solution, heightened drowsiness and a desire to return to the code editor before sleep creeps in warrants getting to the point. If you'd like for me to update this post and expand on one or two additional intermediate solutions that build off of the previous approach and the pros/cons therein please drop a comment letting me know below! Phase Three -- The Utility of .d.ts files First, head to your tsconfig.json file to ensure that the following flag is set -- "declaration": true The contents of my current tsconfig.json (as of 2022-03-24) { "compilerOptions": { "module": "esnext", "target": "ES2020", "lib": ["DOM", "DOM.Iterable", "ESNext"], "declaration": true, "strict": true, "pretty": true, "noImplicitAny": true, "strictNullChecks": true, "noImplicitThis": true, "alwaysStrict": true, "skipDefaultLibCheck": true, "moduleResolution": "Node", "sourceMap": true, "strictBindCallApply": true, "noStrictGenericChecks": false, "strictFunctionTypes": true, "noUnusedLocals": false, "noUnusedParameters": false, "jsx": "preserve", "downlevelIteration": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "inlineSources": true, "experimentalDecorators": true, "strictPropertyInitialization": true, "baseUrl": "./", "allowJs": true, "sourceRoot": "./src", "checkJs": false, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "resolveJsonModule": true, "allowSyntheticDefaultImports": true, "isolatedModules": true, "incremental": true, "paths": { "@/apollo/*": ["src/apollo/*"], "@/components/*": ["src/components/*"], "@/graphql/*": ["src/graphql/*"], "@/hooks/*": ["src/hooks/*"], "@/lib/*": ["src/lib/*"], "@/pages/*": ["src/pages/*"], "@/styles/*": ["src/styles/*"], "@/types/*": ["src/types/*"], "@/utils/*": ["src/utils/*"] } }, "include": [ "next-env.d.ts", "index.d.ts", "graphqls.d.ts", "src/**/*.ts", "src/**/*.d.ts", "src/**/*.graphqls.d.ts", "src/**/*.graphql.d.ts", "src/**/*.graphqls", "src/**/*.graphql", "src/**/*.tsx", "src/**/*.js", "src/**/*.gql" ], "exclude": ["node_modules"] } Enter fullscreen mode Exit fullscreen mode Right, on to the good stuff. With the declaration flag set to true, create a root index.d.ts file. Please be sure to "include" the file at the bottom of your tsconfig.json file within the "include": [] array too (for TS to detect it). index.d.ts // Recursive Optional Mapping good-good declare type RecursiveOptional = { [P in keyof T]?: RecursiveOptional; }; // Strip RecursiveOptional wrapper post-recursion for 1:1 alignment with core react typedefs declare type OmitRecursiveOptionalWrapper = T extends RecursiveOptional< infer U > ? U : T; // strips the recursively conditional helper type for 1:1 alignment with Reacts internal definitions declare const ReactRecursiveUnwrapped = ({ jsxProps }: { jsxProps: Partial< OmitRecursiveOptionalWrapper< RecursiveOptional< JSX.IntrinsicElements > > >; }) => ({ ...jsxProps }); // TypeDef to use Globally declare type ReactUnwrapped< T extends keyof ReturnType > = { [P in T]?: ReturnType[P]; }; Enter fullscreen mode Exit fullscreen mode Let's break this down: OmitRecursiveOptionalWrapper and RecursiveOptional are both helper types. RecursiveOptional conditionally maps all the props in . The [P in keyof T]?: notation indicates that every property mapped is made conditional by the ?: operator. If that were instead [P in keyof T]-?: then every property mapped would be stripped of its conditional status and made required. If your aim is to avoid manipulating the required vs conditional status for any given mapped property, simply omit the question mark altogether [P in keyof T]:. OmitRecursiveOptionalWrapper is the yin to RecursiveOptional's yang in this context. How? Why? The Omitting Wrapper strips the transformed (conditionally mapped) output type of the RecursiveOptional typedef, which otherwise clashes with React's typedefs under the hood leading to errors. The OmitRecursiveOptionalWrapper type declaration may look familiar -- recall the config for the UnwrapPromise type from Phase One: declare type OmitRecursiveOptionalWrapper = T extends RecursiveOptional< infer U > ? U : T; Enter fullscreen mode Exit fullscreen mode Breakdown of what's happening in the Omit Wrapper above: T extends any RecursiveOptional-Wrapped property U and infers its type if T does indeed extend or encounter such a configuration, it only returns the inner property U which consequently eliminates the outer RecursiveOptional type in the process else, if it does not encounter a RecursiveOptional wrapped type, it simply returns T The Bread'n'Butter If you've made it this far I extend my thanks, may the force of generics be with you. Now the good stuff -- let's examine the two remaining declarations in question. The first, ReactRecursiveUnwrapped is a const that returns a destructured/spread jsxProps of type Partial // strips the recursively conditional helper type for 1:1 alignment with Reacts internal definitions declare const ReactRecursiveUnwrapped = ({ jsxProps }: { jsxProps: Partial< OmitRecursiveOptionalWrapper< RecursiveOptional< JSX.IntrinsicElements > > >; }) => ({ ...jsxProps }); Enter fullscreen mode Exit fullscreen mode Let's take a look at the intellisense for this typedef: But wait -- there are more typedefs assigned to the type of jsxProps initially...but also -- recall the yin/yang dynamic of the two helper types. OmitRecursiveOptionalWrapper wraps the RecursiveOptional wrapper to effectively cancel one another out after the internal JSX.IntrinsicElements interface has already been recursively (and conditionally) mapped out by the RecursiveOptional wrapper! Leaving us with a much friendlier typedef to work with -- Partial Lastly, let's examine the ReactUnwrapped> type which we will use globally with 0 imports required declare type ReactUnwrapped< T extends keyof ReturnType > = { [P in T]?: ReturnType[P]; }; Enter fullscreen mode Exit fullscreen mode The intellisense for T, which extends keyof ReturnType -- which is equivalent to keyof ReturnType>-- is as follows: T extends "symbol" | "object" | "a" | "abbr" | "address" | "area" | "article" | "aside" | "audio" | "b" | "base" | "bdi" | "bdo" | "big" | "blockquote" | "body" | "br" | "button" | "canvas" | ... 155 more ... | "view"> Enter fullscreen mode Exit fullscreen mode The ReturnType for the declared const ReactRecursiveUnwrapped is equivalent to the definition of the JSX-namespace-residing IntrinsicElements{} interface { a?: React.DetailedHTMLProps, HTMLAnchorElement> | undefined; ... 173 more ...; view?: React.SVGProps<...> | undefined; } Enter fullscreen mode Exit fullscreen mode The only discernible difference? The recursive optional mapping, indicated by [P in T]?: within the ReactUnwrapped declaration, results in each JSX.IntrinsicElement having a conditionally undefined union type Type |undefined Ultimately, the globally utilized type has the following general shape: type ReactUnwrapped = { [P in T]?: { a?: React.DetailedHTMLProps, HTMLAnchorElement> | undefined; ... 173 more ...; view?: React.SVGProps<...> | undefined; }[P] | undefined; } Enter fullscreen mode Exit fullscreen mode Since these types are declared in a root index.d.ts file they are automatically available for global consumption with zero imports required. To recap, these four declarations are of immediate utility for our purposes: declare type RecursiveOptional = { [P in keyof T]?: RecursiveOptional; }; declare type OmitRecursiveOptionalWrapper = T extends RecursiveOptional< infer U > ? U : T; declare const ReactRecursiveUnwrapped = ({ jsxProps }: { jsxProps: Partial< OmitRecursiveOptionalWrapper< RecursiveOptional< JSX.IntrinsicElements > > >; }) => ({ ...jsxProps }); declare type ReactUnwrapped< T extends keyof ReturnType > = { [P in T]?: ReturnType[P]; }; Enter fullscreen mode Exit fullscreen mode Consuming the ReactUnwrapped type in .tsx files Vercel tends to use a top-level Page component to wrap an apps Layout with. This Page component is adapted from Vercel's new @vercel/examples-ui package, the codebase for which can be found here Consider injecting a JSX.IntrinsicElement with all of its native props to make them available for consumption anytime the Page component is used elsewhere as follows: export const Page: FC> = ({ children, ...props }) => ( {children} main> ); Enter fullscreen mode Exit fullscreen mode Noteworthy mention Notice how children (aka ReactNode) is passed into props, provided by the outer React Functional Component type wrapper, FC>. Recently, VFC, or Void Functional Component has become increasingly popular over the past year, being cited as better practice as it doesn't automatically inject every component in which its used with ReactNode (children). But what about the children passed in? Coincidentally, when using the ReactUnwrapped<"main"> type, all of the Intrinsic Elements props are injected including children. The above Page component can be rewritten as follows: export const Page: VFC> = ({ ...props }) => ( {props.main?.children} main> ); Enter fullscreen mode Exit fullscreen mode Fantastic! This works for , , , , and just about every other Intrinsic Element. With the global ReactUnwrapped helper you can repurpose its intrinsic children (ReactNode) prop to wherever is deemed most fitting. Last but not least, an example with an SVG Example of injecting and using a GitHub Icon: import type { VFC } from "react"; const GitHubIcon: VFC> = ({ svg, path }) => ( {svg?.children ? svg.children : <>} svg> ); export default GitHubIcon; Enter fullscreen mode Exit fullscreen mode Consuming export const CustomDiv = ({ div }: ReactUnwrapped<"div">) => (
    { e.preventDefault(); e.currentTarget.style.cssText.replace( "GitHubIcon", "Changing Text Underway" ); } }} path={{ name: "GitHubIconPath", onMouseOver: e => { e.preventDefault(); // do things } }} /> {div?.children} div> ); Enter fullscreen mode Exit fullscreen mode That's all for now, I'll check back in regularly to answer questions/update and polish this post. Thanks for reading along! You can check out the github repo that the bulk of this code originates from here PS -- Twice a day🎉

Stats

Basic nextjs-headless-wp repo stats
1
3
2.6
about 2 years ago
The modern identity platform for B2B SaaS
The APIs are flexible and easy-to-use, supporting authentication, user identity, and complex enterprise features like SSO and SCIM provisioning.
workos.com