Git Product home page Git Product logo

react-notion-x's Introduction

React Notion X

React Notion X

Fast and accurate React renderer for Notion. TS batteries included. ⚡️

NPM Build Status Prettier Code Formatting NPM

Contents

Advice

If you just want to publish a website using Notion, then we highly recommend using Super.so — a hosted solution with great perf that takes care of all the details for you.

If you want more control over your website via React, then we recommend checking out the accompanying Next.js starter kit, which is free and uses react-notion-x under the hood.

And if you want even more control, then you're in the right place! 👇👇

Features

  • 🚀 Simple - TypeScript + React
  • Fast - 10-100x faster than Notion
    • 95-100% Lighthouse scores
    • Heavier components can be loaded lazily via next/dynamic
  • 💯 Tests - Comes with a comprehensive test suite covering most of Notion's functionality
  • 🔥 Solid - Used in production by Potion and thousands of websites
  • 💪 Smooth - Supports next/image along with LQIP preview images (demo)
  • Framework agnostic - Use with next.js, create-react-app, gatsby, etc

Usage

First you'll want to fetch the content for a Notion page:

import { NotionAPI } from 'notion-client'

const notion = new NotionAPI()

const recordMap = await notion.getPage('067dd719a912471ea9a3ac10710e7fdf')

Once you have the data for a Notion page, you can render it via React:

import * as React from 'react'
import { NotionRenderer } from 'react-notion-x'

export default ({ recordMap }) => (
  <NotionRenderer recordMap={recordMap} fullPage={true} darkMode={false} />
)

Note: for heavier blocks, you'll have to opt into using them via NotionRenderer.components. These are not included in the default NotionRenderer export because they're too heavyweight for many use cases.

Styles

You'll need to import some CSS styles as well. If you're using Next.js, we recommend you place these imports at the top of pages/_app.js:

// core styles shared by all of react-notion-x (required)
import 'react-notion-x/src/styles.css'

// used for code syntax highlighting (optional)
import 'prismjs/themes/prism-tomorrow.css'

// used for rendering equations (optional)
import 'katex/dist/katex.min.css'

Optional Components

The default imports from react-notion-x strive to be as lightweight as possible. Most blocks will render just fine, but some larger blocks like PDFs and collection views (database views) are not included by default.

To use them, you'll need to import the ones you want from react-notion-x/build/third-party/*:

import { Code } from 'react-notion-x/build/third-party/code'
import { Collection } from 'react-notion-x/build/third-party/collection'
import { Equation } from 'react-notion-x/build/third-party/equation'
import { Modal } from 'react-notion-x/build/third-party/modal'
import { Pdf } from 'react-notion-x/build/third-party/pdf'

Note that we strongly recommend lazy-loading these components unless you know you'll need them up front for your use case.

If you're using Next.js, you can use next/dynamic to lazily load them. If your notion content doesn't use one of these heavyweight components, then it won't get loaded into your page. This keeps the initial page bundle small and your website feeling snappy.

import dynamic from 'next/dynamic'

const Code = dynamic(() =>
  import('react-notion-x/build/third-party/code').then((m) => m.Code)
)
const Collection = dynamic(() =>
  import('react-notion-x/build/third-party/collection').then(
    (m) => m.Collection
  )
)
const Equation = dynamic(() =>
  import('react-notion-x/build/third-party/equation').then((m) => m.Equation)
)
const Pdf = dynamic(
  () => import('react-notion-x/build/third-party/pdf').then((m) => m.Pdf),
  {
    ssr: false
  }
)
const Modal = dynamic(
  () => import('react-notion-x/build/third-party/modal').then((m) => m.Modal),
  {
    ssr: false
  }
)

You'll need to enable them by passing them to the components prop of NotionRenderer.

export default ({ recordMap }) => (
  <NotionRenderer
    recordMap={recordMap}
    components={{
      Code,
      Collection,
      Equation,
      Modal,
      Pdf
    }}
  />
)

The Code component uses Prism under the hood. It comes bundled with support for JavaScript, TypeScript, and CSS by default. To add support for additional language syntaxes, follow the example in components/NotionPage.tsx which lazily loads Prism components at runtime.

For Equation support, you'll need to import the katex CSS styles.

For each of these optional components, make sure you're also importing the relevant third-party CSS if needed (above).

Private Pages

You may optionally pass an authToken and activeUser to the API if you want to access private Notion pages. Both can be retrieved from your web browser. Once you are viewing your workpace, open your Development Tools > Application > Cookie > and Copy the token_v2 and notion_user_id. Respectively, activeUser: notion_user_id, authToken: token_v2.

We recommend storing these as environment variables and passing them into the NotionAPI constructor as follows:

const notion = new NotionAPI({
  activeUser: process.env.NOTION_ACTIVE_USER,
  authToken: process.env.NOTION_TOKEN_V2
})

Note that this is not the same as the API token provided by the official Notion API since notion-client uses the unofficial Notion API (which is what all Notion apps use).

Next.js Examples

Here's a minimal Next.js example project with the most important code in pages/[pageId].tsx and components/NotionPage.tsx. You can view this example live on Vercel.

Here's a more full-featured Next.js example project with the most important code in pages/[pageId].tsx and components/NotionPage.tsx. You can view this example live on Vercel.

The full-featured demo adds a few nice features:

  • Uses next/image to serve optimal images
  • Uses preview images generated via lqip-modern
  • Lazily bundles larger optional components via next/dynamic
    • Code
    • Equation
    • Pdf
    • Modal
    • Collection (e.g., notion databases including table and gallery views)

For a production example, check out the Next.js Notion Starter Kit, which uses react-notion-x under the hood.

Packages

Package NPM Environment Description
react-notion-x NPM Browser + SSR Fast React renderer for Notion.
notion-client NPM Server-side* Robust TypeScript client for the Notion API.
notion-types NPM Universal Core Notion TypeScript types.
notion-utils NPM Universal Useful utilities for working with Notion data.

* Notion's API should not be called from client-side browsers due to CORS restrictions. notion-client is compatible with Node.js and Deno.

Supported Blocks

The majority of Notion blocks and collection views are fully supported.

Block Type Supported Block Type Enum Notes
Page ✅ Yes page
Text ✅ Yes text Supports all known text formatting options
Bookmark ✅ Yes bookmark Embedded preview of external URL
Bulleted List ✅ Yes bulleted_list <ul>
Numbered List ✅ Yes numbered_list <ol>
Heading 1 ✅ Yes header <h1>
Heading 2 ✅ Yes sub_header <h2>
Heading 3 ✅ Yes sub_sub_header <h3>
Quote ✅ Yes quote
Callout ✅ Yes callout
Equation (block) ✅ Yes equation katex via react-katex
Equation (inline) ✅ Yes text katex via react-katex
Todos (checkboxes) ✅ Yes to_do
Table Of Contents ✅ Yes table_of_contents See notion-utils getPageTableOfContents helper funtion
Divider ✅ Yes divider Horizontal line
Column ✅ Yes column
Column List ✅ Yes column_list
Toggle ✅ Yes toggle <details>
Image ✅ Yes image <img>
Embed ✅ Yes embed Generic iframe embeds
Video ✅ Yes video iframe
Figma ✅ Yes figma iframe
Google Maps ✅ Yes maps iframe
Google Drive ✅ Yes drive Google Docs, Sheets, etc custom embed
Tweet ✅ Yes tweet Uses the twitter embedding SDK
PDF ✅ Yes pdf Uses S3 signed URLs and react-pdf
Audio ✅ Yes audio Uses S3 signed URLs and HTML5 audio element
File ✅ Yes file Uses S3 signed URLs (generic downloadable file)
Link ✅ Yes text External links
Page Link ✅ Yes page Link to a notion page in the same workspace
External Page Link ✅ Yes text Links to a notion page or collection view in another workspace
Code (block) ✅ Yes code Block code syntax highlighting via prismjs
Code (inline) ✅ Yes text Inline code formatting (no syntax highlighting)
Collections ✅ Yes Also known as databases
Collection View ✅ Yes collection_view Collections have a 1:N mapping to collection views
Collection View Table ✅ Yes collection_view type = "table" (default table view)
Collection View Gallery ✅ Yes collection_view type = "gallery" (grid view)
Collection View Board ✅ Yes collection_view type = "board" (kanban view)
Collection View List ✅ Yes collection_view type = "list" (vertical list view)
Collection View Calendar ❌ Missing collection_view type = "calendar" (embedded calendar view)
Collection View Page ✅ Yes collection_view_page Collection view as a standalone page

Please let us know if you find any issues or missing blocks.

All known blocks and most known configuration settings can be found in our test suite.

Performance

Google Lighthouse Scores
Google Lighthouse scores for an example page rendered by `react-notion-x` on Vercel.

Bundlephobia

Out of the box, react-notion-x is pretty fast and relatively lightweight, but there are a few key factors to be aware of.

Bundlephobia reports a ~27kb gzip bundle size for the main react-notion-x bundle. This doesn't include the optional third-party components which we recommend lazy loading via next/dynamic only if a page needs them.

Another major factor for perf comes from images hosted by Notion. They're generally unoptimized, improperly sized, and not cacheable because Notion has to deal with fine-grained access control that users can change at any time. You can override the default mapImageUrl function on NotionRenderer to add caching via a CDN like Cloudflare Workers, which is what Notion X does for optimal page load speeds.

NotionRenderer also supports lazy image loading with optional low quality image placeholder previews. You can see a demo of this in practice on this page which is using lqip-modern to pre-generate placeholder images that are inspired by Medium.com's image loading.

If you're using Next.js, we recommend passing next/image and next/link to the renderer as follows:

import Image from 'next/image'
import Link from 'next/link'

export default ({ recordMap }) => (
  <NotionRenderer
    recordMap={recordMap}
    components={{
      nextImage: Image,
      nextLink: Link
    }}
  />
)

This wraps these next.js components in a compatability layer so NotionRenderer can use them the same as their non-next.js equivalents <img> and <a>.

Related

  • Next.js Template - The easiest way to deploy a self-hosted Notion site with Next.js and Vercel.
    • Only takes a few minutes to setup!
    • Uses react-notion-x under the hood
  • Notion Test Suite - Comprehensive suite of Notion test pages
  • react-notion - Original react renderer for notion
    • react-notion-x started as a fork of react-notion with better support for different types of Notion content (especially collections) and grew into something much more comprehensive
    • react-notion is no longer actively maintained
  • notion-api-worker - Notion API proxy exposed as a Cloudflare Worker
    • notion-types and notion-client are a refactored fork of notion-api-worker.
    • One of the main use cases for react-notion-x is server-side rendering via Next.js, in which case the CF worker is unnecessary
    • We recommend that you use notion-client instead
  • notion-api-agent - Alternative Notion API client
  • notion-py - Excellent Python wrapper around the Notion API

Contributing

See the contribution guide and join our amazing list of contributors!

License

MIT © Travis Fischer

This project extends MIT-licensed work by Timo Lins, Tobias Lins, Sam Wight, and other contributors.

Big thanks to Noah Bragg who runs Potion.so for helping to maintain react-notion-x.

Support my OSS work by following me on twitter twitter

Sponsor

Super.so has been kind enough to sponsor this project. If you're looking for a hosted solution that takes a very similar approach to react-notion-x but handles all of the details for you, then definitely check them out.

React Notion X

react-notion-x's People

Contributors

alandecode avatar bytrangle avatar ciiiii avatar enpitsulin avatar frankcbliu avatar futantan avatar ggiande avatar harrisjose avatar hugocxl avatar jaesang1998 avatar julbrs avatar junogueira avatar kidonng avatar mannyyang avatar marekhvolka avatar michaelcasadev avatar nabettu avatar normdoow avatar oudmane avatar pbteja1998 avatar remorses avatar s4nju avatar shellbear avatar shunkakinoki avatar stefanfeldner avatar transitive-bullshit avatar utkarshbhimte avatar utkuturunc avatar wustep avatar xissy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-notion-x's Issues

The example don't run very well

I cloned this repo, and did not modify anything. Then I try run the example in localhost, but the collections disappeared.
image

Is this because I skipped some essential steps ?

Flag emojis missing on Windows 10

Hello and thanks for this great project,
I've found a small issue if you use flag emoji's and preview the build on Windows.

How to reproduce: Use emoji flags in a notion document and preview on Windows 10.

The issue can be reproduced here:
https://istvan.design/#66c1fc59b57146aca26b4c0e9c6e0130

In Notion.so the emojis are automatically replaced with the ones from Mac OS, maybe there is a way to do this with a CDN and emoji svgs in this library ?

Images in collection not loading and gallery view different

HI, so I am trying to render this Notion page: https://www.notion.so/db65f3788ccd476a9309d6f66bf775de

However, none of the images load. I am getting:

Failed to load resource: the server responded with a status of 400 ()

Also, the view ends up looking a bit different.
Screenshot 2021-02-02 at 11 59 40 am

Any idea what I am missing?

Here is my source code:

import React from "react";
import Head from "next/head";

import { getPageTitle, getAllPagesInSpace } from "notion-utils";
import { NotionAPI } from "notion-client";
import { NotionRenderer, Collection, CollectionRow } from "react-notion-x";

const notion = new NotionAPI();

export const getStaticProps = async (context) => {
  const pageId = "db65f3788ccd476a9309d6f66bf775de";
  const recordMap = await notion.getPage(pageId, {
    fetchCollections: true,
    signFileUrls: false,
  });

  console.log("RECORD MAP", recordMap);

  return {
    props: {
      recordMap,
    },
    revalidate: 10,
  };
};

export async function getStaticPaths() {
  const paths = [];

  return {
    paths,
    fallback: true,
  };
}

export default function NotionPage({ recordMap }) {
  if (!recordMap) {
    return null;
  }

  const title = getPageTitle(recordMap);

  return (
    <>
      <Head>
        <meta name="description" content="Supported Games on Bunch" />
        <title>{title}</title>
      </Head>

      <NotionRenderer
        components={{
          collection: Collection,
          collectionRow: CollectionRow,
        }}
        recordMap={recordMap}
        fullPage={true}
        darkMode={false}
      />
    </>
  );
}

Create React App

My apologies if this is a stupid question, I'm trying to add react-notion-x into my create-react-app and I keep getting the following error when I follow your example:

./node_modules/react-notion-x/build/esm/block.js
Module not found: Can't resolve 'next/dynamic' in '/Users/.../node_modules/react-notion-x/build/esm'

What am I doing wrong? Is this for Next.js applications only or can I use it with create-react-app?

Group title + icon + cover in the same div.

Thanks for this amazing resource, it would be nice if the main page title can be grouped together with the cover image, just like super.so templates, also main page title to be <h1> tag instead of <span>

image

Example:

<div class="notion-page__header">
    <div class="notion-page__cover">
        <img src="/cover-img.jpg"/>
    </div>
    <div class="notion-page__title">
        <h1>This is the page title</h1>
    </div>
<div/>
<div class="notion-page__content">
...
</div>

I'm happy to help with a pull request on this if you can provide me a little bit of guidance on where to edit this, I just dicovered this library recently and i'm not very familiar with it.

Prop `className` did not match

Hello, thank you for your great project.

I have an issue.
I rendered my notion page using react-notion-x in my next.js project, and this error sometimes occurred.

Warning: Prop "className" did not match. Server: " language-bash" Client: "language-bash"

I found that the class name of code block has space at the front.

<pre class="notion-code language-bash">
  <code class=" language-bash">

Only code block has this issue.
Do you know how to solve this problem?

TypeError: Cannot read property 'length' of undefined

Thanks for the awesome project!

I get an error whenever I'm trying to load a database that is a page

TypeError: Cannot read property 'length' of undefined
    at Object.exports.getPageTableOfContents (/Users/shunkakinoki/ghq/github.com/shunkakinoki/shunkakinoki.com/node_modules/notion-utils/build/cjs/get-page-table-of-contents.js:42:46)
    at exports.Block (/Users/shunkakinoki/ghq/github.com/shunkakinoki/shunkakinoki.com/node_modules/react-notion-x/build/cjs/block.js:75:39)
    at processChild (/Users/shunkakinoki/ghq/github.com/shunkakinoki/shunkakinoki.com/node_modules/react-dom/cjs/react-dom-server.node.development.js:3373:14)

Option to hide header (top nav)

It would be nice to have the option to remove the notion-header when fullPage is set to true, instead of hiding it through css

How do you get collection data header values?

How would I be able to fetch the collection property names using getCollectionData??

I am using the below snippet to get the format of the collection data, but it's coming jumbled up except for the first column.

Object.keys(collectionView).forEach((cid) => {
    console.log(collectionView[cid].value.format);
  });

Format of the data:

{
  table_wrap: true,
  table_properties: [
    { width: 276, visible: true, property: 'title' },
    { width: 200, visible: true, property: '3x=Q' },
    { width: 200, visible: true, property: 'S)s,' },
    { width: 411, visible: true, property: 'o+,#' }
  ]
}

If it helps, I'm trying to build a simple blog with the index page holding the links to all the different pages based on their slug and not the pageId.

Public link for the collection: https://www.notion.so/hamzamoiyadi/52db845d75fb4e8396b66234f05caecb?v=afb3d901772e474195c013570f511696

Add support for rehype / remark

Thank you for this great library, it would be cool if we could have support for rehype / remark plugins so we can extend our code blocks with line numbers / file names etc.

Error: Notion page not found "xxxxxxxx"

Problem

The Notion page is not loading, showing Error: Notion page not found "b23d2d383bbe49a0bb983837cc486862"

Reproduce

Create a notion page in personal free account and https://www.notion.so/Testtt-b23d2d383bbe49a0bb983837cc486862 copy the page id from the page url and pass to await notion.getPage('b23d2d383bbe49a0bb983837cc486862') it gives Error: Notion page not found "b23d2d383bbe49a0bb983837cc486862"

Expected Behaviour

It should show the page and this was working before and not sure which recent update caused this issue.

Thanks in advance

Whenever I click on image, I get an error relating to the zoomContainer being null.

Screen Shot 2021-01-24 at 4 11 41 PM

Whenever I click on image, I get an error relating to the zoomContainer being null.

"TypeError: null is not an object (evaluating 'zoomContainer.getBoundingClientRect')"

The notion page id I am rendering: 8e7024e994cb425fb70429e7b20915ff

My code

      <Container>
        <Center>
          <NotionRenderer
            recordMap={recordMap}
            fullPage={false}
            darkMode={false}
          />
        </Center>
      </Container>

I know the expected behavior is that the image pops up in a zoomed form. Not sure what I am doing wrong here. Any advice?

Person property and person text support

Hey @transitive-bullshit

Problem 1

Person property is not rendered in the property list on the top of the page if no other mentions of this user exist on the page below. The error is reported by react-render-x is: missing user 5693XXXX-XXXX-45db-XXXX-a3166058XXXX

notion react-notion-x
image image

Problem 2

As soon as at least a single mention happens on the webpage, the property now gets resolved, with the only problem it rendering only the image without a name text.

Also please note, on the text style the name mention should not even have the image preview and should be rendered as an inline-block but it is treated like a regular block.

notion react-notion-x
image image

Are there ways to provide a custom component for rendering specific properties or persons/users?

Cheers!

How can I edit in collectionTableView

I hava a share link which can edit when I share others.
https://www.notion.so/database-78617effcc6941148c582686021d14d0

I add component in render like this.
<NotionRenderer recordMap={recordMap} showTableOfContents={false} showCollectionViewDropdown={true} fullPage={true} darkMode={false} components={{ equation: Equation, code: Code, collection: Collection, collectionRow: CollectionRow }} />
And goto http://localhost:3000/database-78617effcc6941148c582686021d14d0

It will show collection view table,but can not edit.Is collection view table support edit?

Image modal option for collection view to act as an image gallery

https://daniell.dev/about on my page I am rendering a collection view which acts as an image gallery, currently I mapped the page links to link to the relevant Notion page, however when you only care about displaying the images this is not ideal.

It would be nice if there was an option to show an overlay when clicking one of the collection items, like what you see when clicking the image on the actual Notion page https://www.notion.so/b123f51caf3e4d3485fc99190a4ecc39, this way the collection can act as an image gallery

TypeForm Embed Grabs Focus

Here is a notion page I am testing with: 130868ef58d949f4add8cf1da983fc16

The page will jump down to give the typeform iframe focus once it loads.
Not sure what the best way to handle this is. Seems like there is no way we can take focus away from the iframe itself since it is controlled by typeform (maybe I'm wrong on this).

One solution I was playing around with was trying to give focus to another element after the iframe loads.

content = (
            <>
              <input style={{position: 'absolute', marginTop: -500}} ref={ref} />
              <iframe
                className='notion-asset-object-fit'
                style={assetStyle}
                src={src}
                title={`iframe ${block.type}`}
                frameBorder='0'
                // TODO: is this sandbox necessary?
                // sandbox='allow-scripts allow-popups allow-top-navigation-by-user-activation allow-forms allow-same-origin'
                allowFullScreen
                // this is important for perf but react's TS definitions don't seem to like it
                loading='lazy'
                onLoad={() => setTimeout(() => ref.current.focus(), 800)}
              />
            </>
          )

This is in components -> asset.tsx

But this is not a great solution because the focus time could depend on the load time or network.

Add support for Bearer Authorization

The official Notion API allows integrations to request Notion data using a Bearer token (which may be the integration token, or an access token from Oauth). This must be passed an an authorization header: Authorization: Bearer {MY_NOTION_TOKEN}.
It looks like currently only an auth token is supported, which is passed as a cookie. It'd be great if react-notion-x could support the Bearer header as well, so that it can be used to request page data for a Notion integration.

Relevant docs: https://developers.notion.com/docs/authorization#overview

Edit: it looks like this is more work than just switching auth, different URLs altogether. Might be a dupe of #66

Tweet embeds not working

Hey maintainers.

There is a bug on tweet embeds
image

I am currently implementing this on a NextJS project

react-notion-x version: 4.3.7

What needs to be done here?

Webpack 5 Adoption

I want to use the 3x Faster Refresh feature that comes with Next.js 10.1, but I'm getting an error from react-notion-x.

Source: Webpack 5 Adoption

I get errors when I add this code block to next.config.js file:

module.exports = {
  future: {
    webpack5: true,
  },
}

Error Message:

./node_modules/react-notion-x/build/esm/index.js
Module parse failed: 'import' and 'export' may appear only with 'sourceType: module' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> export * from './types';
| export * from './utils';
| export * from './context';

Obviously, I don't know the webpack side, I'm not sure the problem is with my configurations. I'd appreciate it if you'd help me.

Thanks.

How to integrate with Chakra-UI?

Hey! I just wanted to know if there is a guide on how to map (like with MDX components) each notion block with a custom chakra-ui component. For example, an h1 header on Notion could be mapped with a component in chakra. Also, what would happen when notion finally makes public their own API?

Untitled Pages Issue

I had build issues when a page title is untitled. I believe react-notion-x is throwing an error in this case. I may be wrong about that. Could be in my own system.

These two pageIds has an untitled title. After giving them the build worked correctly.
d2a2831d28f74d8c9beee87f928f3d4e
d87f50f366994182b0037adb130f18f2

image

How to get all blog in notion

in react-notion, i used api /table to get all blogs in my notion.
but in react-notion-x, how to get all blogs in my notiob using table templates

Styling error and audio's caption is not shown in render

Hi,

I am a huge fan of react-notion-x, and I love to use react-notion-x to render my blog and my open source project.

However, there're couple tiny issues, feel free to check this playground site: react-notion-playground.vercel.app

  • Audio's caption is not shown
  • Database style error (horizontal scroll and table header and table body are not properly aligned)
  • Width error when nesting a code block under another block

Here's the code to reproduce: codesandbox.io/s/jolly-currying-yonc6

How to get all page and render

I get this error on first render of page
https://sv1.picz.in.th/images/2021/05/28/Ps3Wbb.png

error message

react-dom.development.js?61bb:67 Warning: Prop `d` did not match. Server: 
"M2 0h10a2 2 0 012 2v10a2 2 0 01-2 2H2a2 2 0 01-2-2V2a2 2 0 012-2zm3.75 5.67v2.66h6.75V5.67H5.75zm0 4.17v2.66h5.75a1 1 0 001-1V9.84H5.75zM1.5 5.67v2.66h2.75V5.67H1.5zm0 
4.17v1.66a1 1 0 001 1h1.75V9.84H1.5zm1-8.34a1 1 0 00-1 1v1.66h2.75V1.5H2.5zm3.25
 0v2.66h6.75V2.5a1 1 0 00-1-1H5.75z" 
Client: "M12 1.5H2a.5.5 0 00-.5.5v10a.5.5 0 00.5.5h10a.5.5 0 00.5-.5V2a.5.5 0 00-.5-.5zM2 0h10a2 2 0 012 2v10a2 2 0 01-2 2H2a2 2 0 01-2-2V2a2 2 0 012-2zm1 3h3.5v3.5H3V3zm4.5 0H11v3.5H7.5V3zM3 7.5h3.5V11H3V7.5zm4.5 0H11V11H7.5V7.5z"

my react code

 <NotionRenderer
        recordMap={recordMap}
        fullPage={false}
        darkMode={false}
        components={{
          pageLink: ({
            href,
            as,
            passHref,
            prefetch,
            replace,
            scroll,
            shallow,
            locale,
            ...props
          }) => (
            <Link
              href={href}
              as={as}
              passHref={passHref}
              prefetch={prefetch}
              replace={replace}
              scroll={scroll}
              shallow={shallow}
              locale={locale}
            >
              <a {...props} />
            </Link>
          ),
          code: Code,
          collection: Collection,
          collectionRow: CollectionRow,
          modal: Modal,
          pdf: Pdf,
          equation: Equation,
        }}
      />

contentBlockIds.flatMap is not a function

Hi, really excited about this project! However, when I run it I get the following error: Am I doing something wrong?

(node:37978) ExperimentalWarning: The dns.promises API is experimental
(node:37978) ExperimentalWarning: Readable[Symbol.asyncIterator] is an experimental feature. This feature could change at any time
(node:37978) UnhandledPromiseRejectionWarning: TypeError: contentBlockIds.flatMap is not a function
at NotionAPI. (/Users/jordan/Desktop/game-hub-web/node_modules/notion-client/build/cjs/notion-api.js:109:66)
at step (/Users/jordan/Desktop/game-hub-web/node_modules/notion-client/build/cjs/notion-api.js:44:23)
at Object.next (/Users/jordan/Desktop/game-hub-web/node_modules/notion-client/build/cjs/notion-api.js:25:53)
at fulfilled (/Users/jordan/Desktop/game-hub-web/node_modules/notion-client/build/cjs/notion-api.js:16:58)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:37978) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:37978) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Using it like so:

  const recordMap = await notion.getPage("067dd719a912471ea9a3ac10710e7fdf", {
    fetchCollections: false,
  });

Adjust column width ratio according to the original page

I think this library would be even better if the column width ration reflected what's set in Notion.
The API provides the ratio value for columns types
immagine

This is the original Notion page (taken from the example page)
immagine
Gets turned into this
immagine

This feature is particularly important when dealing with pictures because they try to expand as much as possible, crushing the other columns.

Image height extends Notion block - doesn't look quite like Notion.

@transitive-bullshit I saw you made a change to image height a few commits ago. Trying to understand what the change was for. But I did notice that since then some images have a height that makes them extend the space vertically. Looks different then Notion does.

Here is an example from https://www.notion.so/cerdeira/Hey-I-m-Nico-34712887699841fab1b59e404ba9d73a

With react-notion-x
image

With notion:
image

I can make a fix for this. Just wanted to understand your thinking behind the change.

Uploaded images are not rendering

Hi, I am trying to use this package, but for some reason uploaded images look broken. Unsplash images and images added through links are working ok.

Screenshot 2021-05-16 at 10 12 02 AM

Here when I right-click on the image and select Open image in new tab, the image is properly loading, but it is not being rendered on the actual page. Not sure if I am doing something wrong here. Any help with this would be very helpful.

These are the props that I added. Do I have to add anything else extra to these?

 <NotionRenderer
  recordMap={extendedRecordMap}
  components={{
    code: Code,
    collection: Collection,
    collectionRow: CollectionRow,
    tweet: Tweet,
    pdf: Pdf,
    equation: Equation,
  }}
/>

How do I use math and code blocks?

I was trying to figure out why my quick app using react-notion-x was not displaying formulas.

I decided to use the live test version of the app at
https://react-demo.notionx.so/3d7df5e4a14141c9932465a0aa394217
and discovered the page correctly working.

I then cloned this repository on my local machine, browsed to the test dir, installed dependencies via npm i and ran npm run dev.
When I browse to the same page as before, now on my local machine at
http://localhost:3000/3d7df5e4a14141c9932465a0aa394217
the page is missing formulas, tables and code blocks.

Console was saying
image

The original Notion page is available at this link.

Cannot build within Vercel/next project

Sorry for the newb question, but after adding notion-client to my Vercel/next project, I get these errors:

info  - Creating an optimized production build  
Failed to compile.

ModuleNotFoundError: Module not found: Error: Can't resolve 'tls' in '.../node_modules/resolve-alpn'

So I did the following as the same type of error kept arising:

$ npm install tls net http2 dns dgram

Finally, I am stuck here:

info  - Creating an optimized production build  
Failed to compile.

ModuleNotFoundError: Module not found: Error: Can't resolve 'dgram' in '.../node_modules/native-dns-cache'

Can you please help me understand what I'm missing? Thank you!

Environment

  • node v14.16.0

RequestError: Cannot read property 'startsWith' of undefined

This is the Notion page I am trying to access: https://www.notion.so/How-to-Start-a-Scholarship-on-Atila-e412e194b70b46698133927e760dd294

I am getting the following error:

RequestError: Cannot read property 'startsWith' of undefined
       at Request._makeRequest (~/project_root/node_modules/notion-client/node_modules/got/dist/source/core/index.js:1177:19)
       at Request (~/project_root/node_modules/notion-client/node_modules/got/dist/source/core/index.js:328:28)
       at urlToOptions (internal/url.js:1259:28)
       at Object.request (https.js:279:15)
       at ~/project_root/node_modules/agent-base/patch-core.js:23:20
       at Request._makeRequest (~/project_root/node_modules/notion-client/node_modules/got/dist/source/core/index.js:1124:43)
       at Request (~/project_root/node_modules/notion-client/node_modules/got/dist/source/core/index.js:328:28)
       at process._tickCallback (internal/process/next_tick.js:68:7) name: 'RequestError', code: undefined, timings: undefined }

If it helps, I am using the serverless framework and serverless offline to run my node server in localhost.

Here is my code snippet:

import { NotionAPI } from 'notion-client'
const api = new NotionAPI();
console.log("api", api);
let response;

try {
    // fetch a page's content, including all async blocks, collection queries, and signed urls
    response = await api.getPage("e412e194b70b46698133927e760dd294");
} catch (err) {
    console.log("getNotionPage", { err });
    response = {
        error: err.toString(),
    };
}
return response;

Setting fullPage={true} breaks mobile rendering

Setting fullPage to true <NotionRenderer recordMap={recordMap} fullPage={true} /> makes it unable to scroll the rendered pages on mobile. The same can be observed on the demo site https://demo.notionx.so/, see screenshot captured on iPhone 7 below
IMG_6B2C00006F3F-1

Setting fullPage to false allows mobile scrolling, but obviously loses the icon and header image.

Calculate reading time

Thanks for the awesome library! I was wondering if you ever tried to calculate the average reading time, do you have any idea how we could get all relevant content from blocks as a single string?

Support Calendar view

Has "calendar view" development started?

If there is something I can cooperate with, I would like to cooperate too.

Thanks!

Optional opt-out from moment-zoom effect

It would be awesome to have the option to disable the moment-zoom effect for image blocks.
I can image it being use to create more static-like pages, where only the presence of the image is preferred.

Next.js example redirecting to the "Notion kit page" even after changing the redirects.

I changed the redirects in the config to

'use strict'

const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true'
})

module.exports = withBundleAnalyzer({
  async redirects() {
    return [
      // redirect the index page to our notion test suite
      {
        source: '/',
        destination: '/181d18266b374edfb16296b479XXXXXX',
        // don't set permanent to true because it will get cached by browser
        // while developing on localhost
        permanent: false
      }
    ]
  }
})

And also the root page Id and space Id to:

  const rootNotionPageId = '181d18266b374edfb16296b479XXXXXX'
  const rootNotionSpaceId = '823ffd8b-XXXX-XXXX-XXXX-cf6798a1c2b5'

Yet it still redirects to the notion kit page, which has the id of 067dd719a912471ea9a3ac10710e7fdf

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.