Giter Site home page Giter Site logo

notionx / react-notion-x Goto Github PK

View Code? Open in Web Editor NEW
4.6K 34.0 534.0 3.06 MB

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

Home Page: https://react-notion-x-demo.transitivebullsh.it

License: MIT License

TypeScript 79.72% CSS 20.26% Shell 0.02%
notion notion-api react-notion typescript react nextjs

react-notion-x's People

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

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.

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.

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.

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?

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.

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)

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?

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;

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 ?

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?

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,
  }}
/>

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

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!

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

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

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.

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?

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 ?

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

Support Calendar view

Has "calendar view" development started?

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

Thanks!

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

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?

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.

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

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}
      />
    </>
  );
}

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

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.

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.

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 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

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,
  });

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,
        }}
      />

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?

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.

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

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?

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.