I'm very new to React and Javascript. I am creating a simple search feature using React and Nodejs where you are able to search for tutors. I am trying to print the output of the search using react. My express server sends a response in the form of a string. It looks like the following:
'[{"tutorID":1,"email":"johndoe@sfsu.edu","firstName":"John","lastName":"Doe","courseTeaching":"csc510","imageReference":" http://localhost:3001/john.png "}]'
I want to be able to display every key and its value in the form of a table. Can someone please help me achieve this?
The code for my search in react is given below:
import React, {useState} from 'react';
import "./SearchForm.css";
import SearchIcon from '@mui/icons-material/Search';
import DisplayResults from './DisplayResults.js';
class SearchForm extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedCategory: '',
textSearch: '',
searchResponse: []
};
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState( {
...this.state,
[target.name]: value
});
}
handleSubmit(event) {
event.preventDefault();
let cat = this.state.selectedCategory;
let searchquery = this.state.textSearch;
fetch(`http://localhost:3000/onSubmit?param1=${cat}¶m2=${searchquery}`, {
method: "GET",
headers: {
'Content-type': 'application/json'
}
})
.then((result, err) => result.json())
.then(contents => {
this.setState({ searchResponse: contents}, function() {
console.log(this.state.searchResponse);
})
});
}
render() {
return (
<>
<p className="greeting">Hi, what would you like to search?</p>
<form onSubmit={this.handleSubmit}>
<div className="wrapper">
<select class="theme"
name="selectedCategory"
type="category"
value={this.state.selectedCategory}
onChange={this.handleInputChange}>
<option value="all">Search All</option>
<option value="tutors">Tutors</option>
<option value="Courses">Courses</option>
</select>
<input className="searchBar"
name="textSearch"
type="text"
placeholder="search"
value={this.state.textSearch}
onChange={this.handleInputChange}>
</input>
<div className="searchIcon">
<SearchIcon onClick={this.handleSubmit}/>
</div>
</div>
</form>
<DisplayResults searchResults={this.state.searchResponse}/>
</>
)
}
}
export default SearchForm;
The code for the DisplayResults is below:
import React from 'react';
class DisplayResults extends React.Component {
render() {
return (
<div>{this.props.searchResults}</div>
);
}
}
export default DisplayResults;
Any help would be much appreciated, thank you.