0

I'm comparatively new to ReactJs.

I've already implemented routing. What I need to do next is to make an auto complete search bar which will automatically suggest country name. And when finally the user inputs the country name some data associated with that particular country will be shown on the page:

enter image description here

This is the part I've done till now. And my Search component is as below:

import React from 'react';
import axios from 'axios';
import * as ReactBootstrap from 'react-bootstrap';


class Search extends React.Component{
    
    render(){
        return(
            <ReactBootstrap.Container>
                <ReactBootstrap.Form>
                    <ReactBootstrap.Form.Group controlId="searchCountry">
                        <ReactBootstrap.Form.Control type="text" placeholder="Seach for a country" />
                    </ReactBootstrap.Form.Group>
                </ReactBootstrap.Form>
            </ReactBootstrap.Container>
        );
    }
}

export default Search;

which is being used in Home.js inside /Pages folder:

import React from 'react';
import Search from '../Components/Search';

class Home extends React.Component{
    render(){
        return(
            <div>
                <p>Home page</p>
                <Search/>
            </div>
        );
    }
}

export default Home

so basically whatever I type in the search box it'll become a query string and some data will be shown associated with that

Now my problem is I don't know what to do next. As said I'm new in this sector and I'm probably not searching for the right things. Need some pointers

For reference my

http://localhost:8000/api/v1/countries/test_country

will return

{
  "error": false,
  "data": [
    {
      "country_name": "test_country",
      "type": "Medical",
      "fees": "500 Taka",
      "duration": "3 Months",
      "details": "lorem ipsum dolor mis amet"
    },
    {
      "country_name": "test_country",
      "type": "Tourist",
      "fees": "500 Taka",
      "duration": "3 Months",
      "details": "lorem ipsum dolor mis amet"
    }
  ],
  "country_name": "test_country"
}

N.B: using react-bootstrap and nodejs for backend

1 Answer 1

1

There are a few things that you need to do here

  1. Localstate using the useState hook in react functional component or state object in a class based component
  2. Controlled inputs
  3. OnSubmit function for form submit

1st thing would be to store the search/query in a localState variable for that you can use to store the value of search

for class based component

class Search extends React.Component{

    constructor(props) {
        super(props);
        this.state = {query: ''}; 
      }

    render(){
        return(
            <Container>
                <Form>
                    <Form.Group controlId="searchCountry">
                        <Form.Control type="text" placeholder="Seach for a country" />
                    </Form.Group>
                </Form>
            </Container>
        );
    }
}

in the class based function you can initialize the state by assigning this.state in the constructor

for functional component

import { useState } from 'react

const Search = () => {

  const [query, setQuery] = useState('');
    
        return(
            <Container>
                <Form>
                    <Form.Group controlId="searchCountry">
                        <Form.Control type="text" placeholder="Seach for a country" />
                    </Form.Group>
                </Form>
            </Container>
        );
    
}

useState function return an array with the first element at index 0 is the stateful variable and the second is a function to update it's value. You can pass the default value of your stateful variable as the first argument to the useState function

Now that we have a stateful variable for query, the next step would be to make convert the input into an controlled input.

in controlled inputs we have to set the initial value of the input and we have to update the value of input ourselves

for class based component

class Search extends React.Component{

    constructor(props) {
        super(props);
        this.state = {query: ''}; 
      }

    // I am not sure if we can create arrow functions directly in a class, other way to write this would be to write it as a normal function and then binding the `this` value in the constructor
    handleChange = (e) => {
      this.setState({query: e.target.value});            
    }

    render(){
        return(
            <Container>
                <Form>
                    <Form.Group controlId="searchCountry">
                        <Form.Control value={this.state.query} onChange={this.handleChange} type="text" placeholder="Seach for a country" />
                    </Form.Group>
                </Form>
            </Container>
        );
    }
}

the value prop for the input field is how we set the value of the input (this is shown to the user) and with the onChange prop we update the stateful variable itself.

for functional component

import { useState } from 'react

const Search = () => {
   
  const [query, setQuery] = useState('');
 
  const handleChange = (e) => {
     setQuery(e.target.value)
  }       

        return(
            <Container>
                <Form>
                    <Form.Group controlId="searchCountry">
                        <Form.Control value={query} onChange={} type="text" placeholder="Seach for a country" />
                    </Form.Group>
                </Form>
            </Container>
        );
    
}

Please note : Since you are new to react, I would recommend first learn the basics of react then go for something like a suggestion component as it would require at least the basic understanding of lifecycle methods, controlled inputs, state . that is why i will not be showing you how to make a suggestion component.

Now the last step would be fetch some results onSubmit

for class based component

class Search extends React.Component{

    constructor(props) {
        super(props);
        this.state = {query: '', results: []}; 
      }

    handleChange = (e) => {
      this.setState({query: e.target.value});            
    }

    handleSubmit = async (e) => {
      e.preventDefault() // Prevent a page reload, that is the normal behaviour of the browser 

    const response = // Your fetching logic goes here
   
    this.setState(response.data)

    }

    render(){
        return(
            <Container>
                <Form onSubmit={handleSubmit}>
                    <Form.Group controlId="searchCountry">
                        <Form.Control value={this.state.query} onChange={this.handleChange} type="text" placeholder="Seach for a country" />
                    </Form.Group>
                </Form>
            </Container>
        );
    }
}

for functional component

import { useState } from 'react

const Search = () => {
   
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);
 
  const handleChange = (e) => {
     setQuery(e.target.value)
  }     

  const handleSubmit = async (e) => {
     e.preventDefault(); // Prevent a page reload, that is the normal behaviour of the browser 
   
     const response = await fakeFetch()
     
     setResults(response.data) 
     
  }  

        return(
            <Container>
                <Form onSubmit={handleSubmit}>
                    <Form.Group controlId="searchCountry">
                        <Form.Control value={query} onChange={} type="text" placeholder="Seach for a country" />
                    </Form.Group>
                </Form>
            </Container>
        );
    
}   
Sign up to request clarification or add additional context in comments.

2 Comments

I tried the way you showed, but one thing that I forgot to mention how should I send the response that I get to /Pages/Home where my data will be shown? Cause my search component is only responsible for rendering out search bar A few tips would be appreciated
You can store it in a global store that manages the state of your application. (redux, mobx, react context api, apollo client ). I recommend you watch this tutorial youtube.com/watch?v=4UZrsTqkcW4&ab_channel=freeCodeCamp.org

Your Answer

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