Home > other >  How can I append a react JSX component to html via Javascript
How can I append a react JSX component to html via Javascript

Time:07-02

I created a custom toast component as seen below:

<Snackbar
    open={open}
    autoHideDuration={6000}
    onClose={handleClose}
    message="Note archived"
    action={action}
  />

I don't want to attach it to every page I create in my react app. Instead, I want to create a static function that I can use to call it. Something like this:

Swal.fire(
  'Good job!',
  'You clicked the button!',
  'success'
)

But for this to work, I have to append a component to the HTML. Please how can I achieve this. I tried doing this:

    ReactDOM.render(<OvToast
    content="hello"
    handleClose={() => console.log('this is it')}
    open
    title="success"
    type="success"
  />, document.querySelector('#root'));

but it removes all the content of the page except the toast. Please how do I append Jsx to a HTML? I want to achieve a toast message.

CodePudding user response:

When you use the render() function all the contents of the target element is removed and the new content is loaded. If you want to append the content to existing HTML you can create a new <div> (or any other element) and append the element. Then render the contents in the newly created element.

function App() {
  return <React.Fragment>hello friend</React.Fragment>;
}

const div = document.createElement("div");
document.querySelector("#root").append(div);

const root = ReactDOM.createRoot(div);
root.render(<App />);

// Or if you are using React 17 or lower:
//
//     ReactDOM.render(<App />, div);
//
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="root">
  <p>existing content</p>
</div>

CodePudding user response:

change your mind The correct way is to add that component to app.js.

Then, using redux, set the value of message and boolean etc... to show or hide the component .

Now you can change the value of message and isShow on any page you want using redux.

  • Related