how to add a search component in react?

4.2k Views Asked by At

I am transforming my current app into React, current ap is using jquery and PHP.

current search bar

<ul class="token-input">
    <li class="token-">
        <input name="p"  type="password" autocomplete="new-password" value="" data-open="false" class="form-control" placeholder="password protected.">
    </li>
</ul>

react header

import React from 'react';
import { FormattedMessage } from 'react-intl';

import styled from 'styled-components';
import A from './A';
import Img from './Img';
import NavBar from './NavBar';
import HeaderLink from './HeaderLink';
import messages from './messages';
import SearchBar from '../SearchBar';
import UserNavbar from '../UserNavbar';
import logoImage from './logo.png';
import backgroundImage from './bg.png';
import './Header.css';

const HeaderImage = styled.div`
  background-image: url(${backgroundImage});
`;

/* eslint-disable react/prefer-stateless-function */
class Header extends React.Component {
  render() {
    return (
      <header>
        <HeaderImage className="navbar navbar-primary bg-dark shadow-sm">
          <div className="container d-flex justify-content-between">
            <A
              to="/"
              className="navbar-brand d-flex align-items-center"
            >
              <Img src={logoImage} />
              <span className="slogan d-none d-md-block"> </span>
            </A>
            <SearchBar className="search-bar" />
            <UserNavbar />
          </div>
        </HeaderImage>

        <div className="tab-area">
          <A href="" />
          <NavBar>
            <HeaderLink to="/">
              <FormattedMessage {...messages.recent} />
            </HeaderLink>
          </NavBar>
        </div>
      </header>
    );
  }
}

export default Header;

can anyone please tell me how can I integrate this search field as 1 component inside the header? (and search is getting data from filter contents which are in the body of the website)

1

There are 1 best solutions below

3
On BEST ANSWER

In SearchBar.js:

class SearchBar extends React.Component {
  state = {
    value: '',
  }

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

  handleSubmit = () => {
    const { value } = this.state;

    // do ajax request or something in order
    // to submit and redirect to a different page
    // containing search results
  }

  render() {
    return (
      <ul class="token-input">
        <li class="token-">
          <input
            name="p"
            type="password"
            autocomplete="new-password"
            value={this.state.value}
            data-open="false"
            className="form-control"
            placeholder="password protected."
          />
        </li>
      </ul>
    );
  }
}

Then you would simply need to import the same way you did.