5

i am new to react . when i did a search react application i got the error look like above.my components are,

UserList

import React, { Component } from "react";
import $ from "jquery";
import UserStore from "../../stores/UserStore";
import * as UserActions from "../../actions/UserActions";
import AddUser from "./AddUser";
import moment from "moment";
import Search from "../Search";

$.DataTable = require("datatables.net");

class UserList extends Component {
  constructor() {
    super();
    this.getUsers = this.getUsers.bind(this);
    this.state = {
      users: UserStore.getAll()
    };
    // this.loadUsers();
  }

  componentDidMount() {
    $(document).ready(function() {
      $("#example").DataTable({
        ordering: true
      });
    });
  }

  componentWillMount() {
    UserStore.on("change", this.getUsers);
  }

  componentWillUnmount() {
    UserStore.removeListener("change", this.getUsers);
  }

  getUsers() {
    console.log(" get users called");
    this.setState({
      users: UserStore.getAll()
    });
  }

  loadUsers() {
    UserActions.getUsersList();
  }

  render() {
    console.log("users " + JSON.stringify(this.state.users));
    const userlistitem = this.state.users.map((user, index) => (
      <tr key={index}>
        <td scope="row">{index}</td>
        <td>{user.name}</td>
        <td>{user.username}</td>
        <td>{user.email}</td>
        <td>{moment(user.dob).format("DD-MM-YYYY")}</td>
        <td>{user.address}</td>
        <td>{user.mobile}</td>
        <td>{user.branch}</td>
      </tr>
    ));
    return (
      <div>
        <Search />

        <div
          style={{
            marginTop: 80,
            marginLeft: 150,
            marginRight: 150
          }}
        >
          <div className="card text-white bg-info mb-3">
            <div className="card-body">
              <div className="d-flex justify-content-between">
                <h5>User List</h5>
                <div>
                  <button
                    style={{
                      marginTop: 10
                    }}
                    type="button"
                    className="btn btn-light "
                    data-toggle="modal"
                    data-target="#exampleModalCenter"
                  >
                    Add New User
                  </button>
                </div>
              </div>
            </div>
          </div>

          <table id="example" className="table table-bordered  table-striped ">
            <thead className="thead-dark">
              <tr>
                <th scope="col">#</th>
                <th scope="col">Name</th>
                <th scope="col">User Name</th>
                <th scope="col">Email</th>
                <th scope="col">DOB</th>
                <th scope="col">Address</th>
                <th scope="col">Mobile</th>
                <th scope="col">Branch</th>
              </tr>
            </thead>
            <tbody>{userlistitem}</tbody>
          </table>
          <AddUser />
        </div>
      </div>
    );
  }
}

export default UserList;

Search

import React, { Component } from "react";
import * as UserActions from "../actions/UserActions";
import "../css/search.css";

import ToggleDisplay from "react-toggle-display";
import UserList from "./User/UserList";

class Search extends Component {
  constructor(props) {
    super(props);

    this.state = {
      name: "",
      username: "",
      mobile: "",
      usercreateddate: "",
      show: false
    };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.searchquery = this.searchquery.bind(this);
  }

  handleInputChange(e) {
    const target = e.target;
    const value = target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  searchquery = () => {
    const search = {
      name: this.state.name,
      username: this.state.username,
      mobile: this.state.mobile,
      usercreateddate: this.state.usercreateddate
    };
    console.log("sdsdsd" + JSON.stringify(search));
    UserActions.searchEvents(search);
    this.setState({
      show: true
    });
  };

  //   componentDidMount() {
  //     this.search("");
  //   }

  render() {
    return (
      <div>
        <br />
        <div className="container card card-body">
          <h3>Search Criteria</h3>
          <div className="col-md-12 form-inline " style={{ padding: 8 }}>
            <div className="col-md-3">
              <input
                name="name"
                type="text"
                class="form-control"
                placeholder="Name"
                id="name"
                onChange={this.handleInputChange}
              />
            </div>
            <div className="col-md-3">
              <input
                name="username"
                type="text"
                class="form-control"
                placeholder="User Name"
                id="username"
                onChange={this.handleInputChange}
              />
            </div>
            <div className="col-md-3">
              <input
                name="mobile"
                type="number"
                class="form-control"
                placeholder="Mobile"
                id="number"
                onChange={this.handleInputChange}
              />
            </div>
            <div className="col-md-3">
              <input
                name="usercreateddate"
                type="text"
                class="form-control"
                placeholder="User Created Date"
                id="usercreateddate"
                onChange={this.handleInputChange}
              />
            </div>
          </div>
          <div>
            <button
              type="button"
              className="btn btn-primary"
              onClick={this.searchquery}
              style={{ marginLeft: "491px", marginTop: "15px" }}
            >
              Search
            </button>
          </div>
        </div>
      </div>
    );
  }
}

export default Search;

Store

import { EventEmitter } from "events";
import dispatcher from "../dispatcher/dispatcher";

class UserStore extends EventEmitter {
  constructor() {
    super();
    dispatcher.register(this.handleActions.bind(this));
    this.users = [
      {
        branch: "19",
        name: "Javcbvcsim11",
        username: "zxcv",
        mobile: "5645654",
        email: "[email protected]",
        address: "Demo vcbvcbAddress1",
        dob: "2020-11-06T00:00:00.000+0000"
      },
      {
        branch: "19",
        name: "Javcbvcsim11",
        username: "zxcv",
        mobile: "5645654",
        email: "[email protected]",
        address: "Demo vcbvcbAddress1",
        dob: "2020-11-06T00:00:00.000+0000"
      },
      {
        branch: "19",
        name: "Javcbvcsim11",
        username: "zxcv",
        mobile: "5645654",
        email: "[email protected]",
        address: "Demo vcbvcbAddress1",
        dob: "2020-11-06T00:00:00.000+0000"
      }
    ];

    console.log(" store constructor ");
  }

  createUser(newUser) {
    this.users.push(newUser);
    console.log("new  users lenght " + this.users.lenght);
    this.emit("change");
  }

  getAll() {
    return this.users;
  }
  handleActions(action) {
    switch (action.type) {
      case "RECEIVE_USERS": {
        this.users = action.users;
        this.emit("change");
        break;
      }
      case "CREATE_USER": {
        this.createUser(action.newUser);
        break;
      }
      case "SEARCH_USER": {
        console.log("sadsadsadsadsadsadsadsadsad");
        this.users = action.search;
        this.emit("change");

        break;
      }
    }
  }
}

export default new UserStore();

Action

import dispatcher from "../dispatcher/dispatcher";

import { BASE_URL } from "../utils/AppConstants";

export function getUsersList() {
  console.log("getting the data! ");
  fetch(BASE_URL + "/users")
    .then(res => res.json())
    .then(
      result => {
        console.log("res " + result);
        dispatcher.dispatch({ type: "RECEIVE_USERS", users: result });
      },
      // Note: it's important to handle errors here instead of a catch() block so that
      // we don't swallow exceptions from actual bugs in components.
      error => {
        //  here manage error and close loading;
        console.log("getting error " + error);
      }
    );
}

export function createNewUser(user) {
  console.log("post the data!");
  fetch(BASE_URL + "/saveuser", {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify(user)
  })
    .then(res => res.json())
    .then(
      result => {
        dispatcher.dispatch({ type: "CREATE_USER", newUser: user });
      },
      // Note: it's important to handle errors here instead of a catch() block so that
      // we don't swallow exceptions from actual bugs in components.
      error => {
        //  here manage error and close loading;
        console.log("getting error " + error);
      }
    );
}

export function searchEvents(search) {
  const url =
    BASE_URL +
    `/searchuser?name=${search.name}&username=${search.username}&mobile=${
      search.mobile
    }&usercreateddate=${search.usercreateddate}`;
  console.log(url);
  fetch(url)
    .then(res => res.json())
    .then(
      result => {
        console.log("res jdjdjdjdjdj " + JSON.stringify(result));
        console.log("dfsfsf" + search);
        dispatcher.dispatch({ type: "SEARCH_USER", search: result });
      },
      // Note: it's important to handle errors here instead of a catch() block so that
      // we don't swallow exceptions from actual bugs in components.
      error => {
        //  here manage error and close loading;
        console.log("getting error " + error);
      }
    );
}

i am here using react with flux procedure. Also the data which showing through jquery datatable. the error occurs when i search for the first time suppose by giving username='something' it shows perfectly in my table. The problem occurs when i click the datatable column name or search attached with it it change to the dummy data i already given. also some times the above mentioned error is throwing. if any one can help it will be much appreciable one.

1 Answer 1

14

This issue occurs when you:

  1. Render something using React
  2. Then, you manipulate DOM rendered by React with external script
  3. Now on the next render cycle(re-render), React doesn't find the DOM node it rendered previously as its already modified/removed by external script

I think this piece of code is the culprit:

    $(document).ready(function() {
      $("#example").DataTable({
        ordering: true
      });
    });

There is a nice article to use JQuery DataTable with React here. You can refer it and try to fix your issue or you can try replacing it with React version of DataTable(Eg: react-table).

Note: Avoid using React and JQuery together. This might create problems in long run.

Sign up to request clarification or add additional context in comments.

5 Comments

Is there any solution to modify the dom?
Can you elaborate? Modify the DOM using what? React or the external script?
I was getting this error. I moved the code to a portal, all fixed. Thanks
It's 2021, please don't use jQuery
There is nothing wrong with using jQuery as long as it serves the purpose.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.