diegomura / react-pdf

📄 Create PDF files using React
https://react-pdf.org
MIT License
14.52k stars 1.14k forks source link

React Context not handled correctly (react-redux and react-intl) #522

Open ribx opened 5 years ago

ribx commented 5 years ago

Describe the bug I am using react-redux and react-intl, which both use a provider component and react's context.

When I use a component, in this case on that is connected to the redux store, I get the following error:

Invariant Could not find "store" in the context of "Connect(Compoment)". Either wrap the root component in a , or pass a custom React context provider to and the corresponding React context consumer to Connect(Compoment) in connect options.

Found an issue with react-router, which could be important here:

If you use React Router, something like {() => routes} won’t work. Due to the way context works in React 0.13, it’s important that the children are created inside that function. Just referencing an outside variable doesn’t do the trick. Instead of {() => routes}, write {createRoutes} where createRoutes() is a function that actually creates (and returns) the route configuration.

To Reproduce Steps to reproduce the behavior including code snippet (if applies):

  1. use a component that uses react's context within react-pdf components
  2. exception is thrown

(I have no time to create a minimal code snippet now, but could do so if someone needs it)

Expected behavior react-pdf should be able to render components, that rely on reacts context api

Desktop (please complete the following information):

diegomura commented 5 years ago

A code snippet to replicate this would be great

ribx commented 5 years ago

https://github.com/ribx/react-pdf-test

import React, {Component} from 'react'
import {createStore} from 'redux'
import ReactDOM from 'react-dom'
import {IntlProvider, FormattedMessage} from 'react-intl'
import {Provider as ReduxProvider, connect} from 'react-redux'
import {Document, Page, View, Text, PDFViewer} from '@react-pdf/renderer'

const store = createStore(state => state)

const Connected = connect(state => ({state}))(props => console.log('state', props.state) || props.children)

class App extends Component {
  render() {
    return (
      <div className="App">
        <PDFViewer>
          <Document>
            <Page>
              <View>
                <Text>
                  <FormattedMessage id="test">{s => s}</FormattedMessage>
                </Text>
              </View>
              <View>
                <Text>
                  <Connected>
                    Redux connected component Test
                  </Connected>
                </Text>
              </View>
            </Page>
          </Document>
        </PDFViewer>
      </div>
    )
  }
}

ReactDOM.render(
  <ReduxProvider store={store}>
    <IntlProvider locale="en" messages={{en: {id: "test", defaultMessage: "React PDF Test"}}}>
      <App/>
    </IntlProvider>
  </ReduxProvider>,
  document.getElementById('root'),
)

I think this is somehow connected to how the new context is working, but I have still problems understanding the concept of react-reconciler.

yjose commented 5 years ago

Hi @diegomura, any idea how we can solve this problem. Using context API is a common case.

sirgalleto commented 4 years ago

Hi, just want to mention that I'm having also problems connecting this component to some context, either the Redux one, as well as other used in my current project.

Is there something we can do in order to help you?

cc @diegomura

zeabdelkhalek commented 3 years ago

same issue here, can't inject react intl ... an alternative solution is to connect the parent component and pass data into props but still alternative.

Nases commented 3 years ago

Having same issue on v1.6.12. Can't use react context API.

hotcakedev628 commented 3 years ago

I am having the similar issue.

Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>

Some of my code for React PDF component are following.

import React from 'react';
import PropTypes from 'prop-types';
import {
  Document,
  Page,
  View,
  Text,
  Image,
  StyleSheet,
  Link
} from '@react-pdf/renderer';
import { useDispatch, useSelector } from 'src/store';

const InvoicePDF = ({ data }) => {
  const dispatch = useDispatch();
  const { invoice } = useSelector((state) => state.invoice);

  return (
    <Document>
      ...
    </Document>
  )
}

export default InvoicePDF;

package.json is the following.

    "@react-pdf/renderer": "^1.6.10",
    "@reduxjs/toolkit": "^1.4.0",
SrividyaKK commented 3 years ago

I am having the same issue. Any update regarding the same?

hotcakedev628 commented 3 years ago

I am having the same issue. Any update regarding the same?

@SrividyaKK It's still silent.

potofpie commented 3 years ago

I see there is a version 2 branch. Has anyone tried this in yet? @SrividyaKK Or have the contributors add this yet? @diegomura

SrividyaKK commented 3 years ago

I see there is a version 2 branch. Has anyone tried this in yet? @SrividyaKK Or have the contributors add this yet? @diegomura

Nope. Not me.

joaopedrocoelho commented 3 years ago

I'm using the useContext hook and I always get the value as undefined, any workaround?

dluigirafael commented 3 years ago

Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>

<PDFViewer>
    <LayoutReturn />
</PDFViewer>

...

LayoutReturn  : 
<Document>
    <Layouts layoutsBackgrounds={layoutsBackgrounds} setLayoutsBackgrounds={setLayoutsBackgrounds} />
</Document>

Layouts :
<Page size="A4" style={{ backgroundColor: "tomato" }}>
          {layoutsBackgrounds[1] ? (
            <View
              style={{ color: "white", textAlign: "center", margin: 30 }}
              onClick={() => {
                setNewBg(1);
              }}
            >
              <Text>Img</Text>
            </View>
          ) : (
            <View
              style={{ color: "black", textAlign: "center", margin: 30 }}
              onClick={() => {
                setNewBg(1);
              }}
            >
              <Text>No img</Text>
            </View>
          )}
        </Page>

Same issue

dluigirafael commented 3 years ago

image same with useContext

diegomura commented 3 years ago

This is an issue on the React side unfortunately. There's an open ticket for awhile now https://github.com/facebook/react/issues/17275. I'll try to reactivate that

walosha commented 2 years ago

same issue here, can't inject react intl ... an alternative solution is to connect the parent component and pass data into props but still alternative.

I solved the issue by lift up the state to the parent component. thanks

mtullo27 commented 1 year ago

Hello, I am still having this issue has anyone come to a solution or work around?

markcnunes commented 4 months ago

I am not using react-redux or react-intl but here is what worked for a custom provider I wanted to access within a Document while using PDFViewer.

import { CustomProvider } from './CustomProvider';
import {
  PDFViewer as PDFViewerOriginal,
  PDFViewerProps,
} from '@react-pdf/renderer';

export const PDFViewer = ({ children, ...props }: PDFViewerProps) => {
  return (
    <PDFViewerOriginal {...props}>
      <CustomProvider>
        {/**
         * Due to a known issue with React, Contexts are not accessible by children of the 'react-pdf' PDFViewer.
         * Because 'react-pdf' is a custom renderer and current React limitations, we have to "bridge" contexts.
         * We need to subscribe to a context from within the PDFViewer and "bridge" the context by creating a Provider as a
         * child of the PDFViewer.
         *
         * For more info read this: @link https://github.com/diegomura/react-pdf/issues/522#issuecomment-861545047
         */}
        {children}
      </CustomProvider>
    </PDFViewerOriginal>
  );
};

Here is a possible solution if your provider is more complex and needs to access some data:

import { CustomProvider, CustomContext } from './CustomProvider';
import {
  PDFViewer as PDFViewerOriginal,
  PDFViewerProps,
} from '@react-pdf/renderer';
import { useContext } from 'react';

export const PDFViewer = ({ children, ...props }: PDFViewerProps) => {
  const customContext = use context(CustomContext);
  return (
    <PDFViewerOriginal {...props}>
      <CustomProvider value={customContext}>
        {children}
      </CustomProvider>
    </PDFViewerOriginal>
  );
};

You can read more about this solution here: https://github.com/facebook/react/issues/17275#issuecomment-550322731