1

I'm using React-18.2.0 in my project and I'm getting the below error

Uncaught Error: createRoot(...): Target container is not a DOM element.

I have tried most of the possible solutions that are uploaded to the internet, but unfortunately it didb't help.

The main.js file is:

import React from 'react';
import { createRoot } from 'react-dom/client';

// eslint-disable-next-line no-unused-vars
const User = (props) => {
  const {control, getValues, setValue} = useForm({
    defaultValues: props,
  });
  return (
    <React.Fragment>
      <UserSignin></UserSignin>
    </React.Fragment>
  );
};

const UserSignin = (props) => {
  return (
<div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
    <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
  </div>
  );
};

window.$(() => {

  (() => {
    const user = window.$('#user');
    if (user.length) {
      const root = createRoot(user);
      root.render(
        <User/>
      );
    }
  })();
});

In the html, I have this:

<form action="" method="POST" novalidate>
      <div id="user"></div>
</form>
    ```

Can someone help me please?

kiran
  • 444
  • 3
  • 15

1 Answers1

6

The $ function from jquery returns a special object called a "Wrapped Set". React doesn't know anything about these, so createRoot can't use it. You'll either need to use .get to access the underlying dom element:

const user = window.$('#user');
if (user.length) {
  const root = createRoot(user.get(0));
  root.render(<User/>);
}

Or you could use document.getElementById (this is built in to the browser and does not require jquery):

const userEl = document.getElementById("user");
if (userEl) {
  const root = createRoot(userEl);
  root.render(<User/>)
}
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98