search and auto completion search using javascript and html

0

good I have to do a project using javascrip the library react js and html.

The project consists in making a search bar that completes what I'm writing, this is done using an api and all this is inside a modal. I already have the modal and the search bar made, as well as the code that looks for the information in the api, but for some reason I am not receiving anything when I do imput in the search bar the code is the following:

javascript:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';





function autocompletado(){
document.getElementById("nameR").innerHTML = '';
document.getElementById("usernameR").innerHTML = '';
document.getElementById("emailR").innerHTML = '';
document.getElementById("addressR").innerHTML = '';
document.getElementById("phoneR").innerHTML = '';
document.getElementById("companyR").innerHTML = '';
document.getElementById("websiteR").innerHTML = '';

var UserArray = [];

var j ;

const url = '/users';
fetch(url)
.then((resp) => resp.json())
.then(function(data) {
  for (j=0;j<data.length;j++) {
    var temporal = [];
    temporal[0] = '${data[j].name} '
    temporal[1] = '${data[j].username} '
    temporal[2] = '${data[j].email} '
    temporal[3] = '${data[j].address} '
    temporal[4] = '${data[j].phone} }'
    temporal[5] = '${data[j].company} '
    temporal[6] = '${data[j].website} '

    UserArray[j] = temporal;
  };  
})
.catch(function(error) {
  console.log(JSON.stringify(error));
}); 

 var pal = document.getElementById("myInput").value;
 var tam = pal.length;
 for (var i = 0; i < UserArray.length; i++) {
    var nombre = UserArray[i][0];
    var str = nombre.substring(0,tam);

    if (pal.length <= nombre.length && pal.length != 0 && nombre.length != 0) {
      if (pal.toLowerCase() == str.toLowerCase()) {
        var node = document.createElement("LI");
        var textnode = document.createTextNode(UserArray[i][0]);
        node.appendChild(textnode);
        document.getElementById("nameR").appendChild(node);
      }else {
      alert('no')
    }

    } 
   }
 }


class App extends Component {
  render() {
    return (
  <div className="App">
    <div className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      <h2>Welcome to React</h2>
    </div>
    <p className="App-intro">
      To get started, edit <code>src/App.js</code> and save to reload.
      <h2>Basic Modal </h2>



    </p>




  </div>

    );
  }
}



export default App;

and this is the html code in which I have the search bar and the modal programmed:

<!doctype html>
<html lang="en">
 <head>

 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">      </script>

 <style> 
input[type=text] {
width: 130px;
box-sizing: border-box;
border: 2px solid #ccc;
border-radius: 4px;
font-size: 16px;
background-color: white;
background-image: url('searchicon.png');
background-position: 10px 10px; 
background-repeat: no-repeat;
padding: 12px 20px 12px 40px;
-webkit-transition: width 0.4s ease-in-out;
transition: width 0.4s ease-in-out;
}

/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 150%;
}

input[type=text]:focus {
width: 100%;
}
</style>


</head>

<body> 

<div id="root"></div>

<div class="container">

<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" id="myBtn">Open Modal</button>

<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Add Note  </h4>
      </div>

      <div class="modal-body">
        <h5 class="modal-title">New Note </h5>
        <input type="text" id="myInput" name="search" onkeyup="autocompletado()" placeholder="Search.." title="Type in a name">

        <table id="myTable">
            <tr class="header">
              <th style="width:10%;">Name</th>
              <th style="width:10%;">Username</th>
              <th style="width:10%;">Email</th>
              <th style="width:10%;">Address</th>
              <th style="width:10%;">Phone</th>
              <th style="width:10%;">Company</th>
              <th style="width:10%;">Website</th>
            </tr>

              <tr >
                <td  id = "nameR"></td>
                <td  id = "usernameR"></td>
                <td  id = "emailR"></td>
                <td  id = "addressR"></td>
                <td  id = "phoneR"></td>
                <td  id = "companyR"></td>
                <td  id = "websiteR"></td>
              <tr>



          </table>
         <ul id="author2s"></ul>
      </div>
      <div class="modal-footer">
        Import: <input type="checkbox" id="myCheck">
        <button type="button" class="btn btn-default" data-dismiss="modal">Add Note</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">cancelar</button>
    </div>

  </div>
</div>

<script>
     $(document).ready(function(){
   $("#myBtn").click(function(){
      $("#myModal").modal();
      console.log("funciona");
    });
 });
</script>


  </body>
</html>

PS: the last two blocks of code are just one, I do not know why you can not put them in the same block

the code runs well, as I said before when I do the imput in the search bar does nothing, try putting other search bar codes in javascript and what I can conclude is that I'm not getting the imput of the bar to be able to do the necessary searches to complete the information

    
asked by lewa14 04.02.2017 в 23:55
source

1 answer

0

Analyzing your code I see some weird things. For example:

  • You have the HTML code in the .html file. If you use React this code should be inside a component, to be used when required (reuse).
  • You do not use status. When you do not use a state in React, you lose everything that the framework gives you. It's like using pure JavaScript.
  • You get the API data outside the component. Bad, because it does not assure you that when assembled into a component, the data obtained will be available.
  • You do many things to search by name, when all you need to do is filter the user array to get those whose name contains the string entered in the input search.

How to get data

The way you get the data is wrong. In React, the data obtained by AJAX must be in the special function componentDidMount , and then the component state must be updated, which will cause the function render to be executed, thus maintaining the UI always synchronized.

How to write a component

As I have already told you, the React components must contain the HTML code to be displayed. A component, as a rule, is reusable whenever a seamless coupling between functionalities is sought. For example, a modal can be reusable if you pass the data from outside the component (such as properties and children), which prevents you from writing the same component for each modal you have.

Here is an example "Reactizado" of your current code:

class App extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      users: [],
      filteredUsers: []
    };
  }

  /**
   * Aquí haces tu consulta a la API
   * y obtienes los usuarios
   */
  componentDidMount () {
    fetch('/users')
      .then((resp) => resp.json())
      .then((users) => {
        this.setState({ users });
      })
      .catch(function(error) {
        console.log(error);
      });
  }

  render () {
    return (
      <div className="modal">
        ...
        <input type="search" id="myInput" placeholder="Search user by name" onChange={this.search.bind(this)} />
        ...
        <table>
          <thead>
            <tr>
              <th>Name</th>
              <th>Username</th>
              <th>Email</th>
              <th>Address</th>
              <th>Phone</th>
              <th>Company</th>
              <th>website</th>
            </tr>
          </thead>
          <tbody>
          {
            this.state.filteredUsers.map((user) => (
              <tr>
                <td>{user.name}</td>
                <td>{user.username}</td>
                <td>{user.email}</td>
                <td>{user.address}</td>
                <td>{user.phone}</td>
                <td>{user.company}</td>
                <td>{user.website}</td>
              </tr>
            ))
          }
          </tbody>
        </table>
      </div>
    )
  }

  /**
   * Busca en el array de usuarios
   */
  search (e) {
    let value = e.target.value;
    // hace un filtrado del array de usuarios para obtener
    // aquellos cuyo nombre contiene lo ingresado en el input
    let filteredUsers = this.state.users.filter((user) => {
      return user.name.includes(value);
    });
    // actualiza el estado y por ende, la tabla
    this.setState({
      filteredUsers
    });
  }
}
    
answered by 05.02.2017 / 00:36
source