0

I have a content.tsx file with the following code:

import React from "react";
import {createPortal} from 'react-dom';

import Text from './Text';

console.log(`Content script...`);

createPortal(
    <Text/>,
    document.body
);

"Text" component code:

import React from 'react';

const Text = () => {
    return (
        <div>
            Just text...
        </div>
    );
};

export default Text;

My manifest includes:

...other keys
"content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["./static/js/content.js"],
      "run_at": "document_end"
    }
]

As you can see, the file is loaded and the message Content script ... is printed in the console. https://i.stack.imgur.com/GS0gK.png

But the div with the text Just text... was not added to the body, in other words, createPortal does not work. https://i.stack.imgur.com/j2geh.png

  • Do it inside an iframe ([general example](https://stackoverflow.com/a/25100953)) e.g. with react-frame-component. – wOxxOm Nov 15 '21 at 13:30

1 Answers1

1

you need to write createPortal inside return or render,

like this:

render() {
    return ReactDOM.createPortal(
         this.props.children,
         document.body
     );
}
Pradip Dhakal
  • 1,872
  • 1
  • 12
  • 29
  • I've created an codesandbox for you, and it's working perfectly fine, can you check it out: https://codesandbox.io/s/wizardly-cache-2vfby?file=/src/content.jsx – Pradip Dhakal Nov 15 '21 at 13:27
  • I checked, the code does not work in my case, but I was able to understand the nature of my problem, thanks. – user17418364 Nov 15 '21 at 13:46