1

I am new to react js, I have a home screen with search bar. where user retrieves an employee information by providing the id. here's the code for that.

const [firstNames, setFirstNames] = useState("");
<input
            value={name}
            type="text" 
            id="header-search"
            placeholder="Enter the search term"
            name={'id'}
            onChange={handleChange}
            />
        
        <button onClick={HandleSearch}>Search</button>

const handleChange= (e) => {
    e.preventDefault();
    setName(e.target.value);
  }

const HandleSearch = e => {

    
    e.preventDefault();
    axios.get(`http://localhost:8080/search?id=`+name)
        .then(response => {
          setLoading(false);
          if(response.status == 200 && response != null){
            
              console.log("RES",response.data);
              var tmpArray= [];
              var tmpJsx =[];
              // I was checking to see if I could retrieve the data from my response.
              var dataparse = response.data;
              var length = dataparse.length;
              console.log("length of my response array is: "+length)

              //printing the elements in array
              for (var i=0; i< length; i++){
                
                //console.log(response.data[i].firstname);
                
                 setFirstNames((firstNames) => [...firstNames, response.data[i]]);
                
              }

              
          } else{
                console.log('problem fetching');
            }
        })
        .catch(error => {
          setLoading(false);
          console.log("error occured: "+error);
        });
}

and here's my return function:

{firstNames.map(function (names, index) {
                  return (
                    <tr key={index}>
                      <td> {names.firstname} -</td>
                      <td> {names.lastname}</td>
                    </tr>
                   )
                })}

How do I add the headers to this data. for example

firstname lastname
abc        abclast

i tried to put this in the map function, but then my data was looking like:

firstname lastname
abc        abclast
firstname lastname
def        deflast
firstname lastname
ghi        ghilast

Im sure there is something that im missing, could anyone help me on how to achieve this: thank you.

firstname lastname
abc        abclast
def        deflast
ghi        ghilast
5
  • when I do that, headers are displayed on the home page. I want them to be displayed only when user hits on search and then display the data along with the headers. Commented Feb 7, 2022 at 17:27
  • If i understand right your backend is returning an array of objects ? Object having first name and last name. If so, you can append at index 1 a custom object that has harcoded values like "First Name" and "Last Name" to display. Also if by "headers" you mean like table headers I would suggest to change the wording as it sounds like HTTP headers at first glance. Commented Feb 7, 2022 at 17:29
  • you can do conditional rendering like {firstNames.length > 0 && put the headers here} Commented Feb 7, 2022 at 17:30
  • that's correct, backend returns an array of objects. Could you give me an example on how to do a conditional rendering? Commented Feb 7, 2022 at 17:31
  • @cmgchess has given an answer for conditional rendering, but you can find docs here: reactjs.org/docs/conditional-rendering.html for more info. Commented Feb 7, 2022 at 17:48

1 Answer 1

2

You can do a conditional rendering by checking if the array has length greater than 0

An example would be like this. You can apply similarly to your problem

let names = [
  {firstName: 'John',lastName: 'Cena'},
  {firstName: 'Rey',lastName: 'Mysterio'},
]

const App = props => {
  return (
    <div>
      {names.length > 0 && <table> //table renders only when array has elements 
        <tbody>
        <tr>
        <th>First Name</th>   //setting headers
        <th>Last Name</th>
        </tr>
        {names.map((name,index) => {       //mapping for individual rows
          return (
            <tr key={index}>
              <td>{name.firstName}</td>
              <td>{name.lastName}</td>
            </tr>
          )
        })}
        </tbody>
      </table>}
    </div>
  );
};

codesandbox demo

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

2 Comments

perfect, this helped. thank you sir.
how do I export the table data thats returned to a csv file?

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.