Home > OS >  ReactJS // SearchBar onClick button
ReactJS // SearchBar onClick button

Time:09-10

I created this search bar for an API. As you can see, the search bar is working with an onChange event. The user is searching the movie thanks to the title. I would like to search a movie with an onClick event with the button. For example, I'm searching Titanic, only this movie must appear.

<form action='/' methode='get' className='Search-Bar'>
  <input
    type='text'
    id='searchbar'
    className='searchbar'
    placeholder='Rechercher un titre, un réalisateur...'
    onChange={(e) => {
      setSearchMovie(e.target.value);
    }}
  />
  <button className='search-button'>
    <AiOutlineSearch /> OK
  </button>
</form>

This is my code for the filter :

const allMovies = movies
.filter((value) => {
  if (searchMovie === '') {
    return value;
  } else if (value.title.includes(searchMovie)) {
    return value;
  }
})
.map((movie, index) => {
  return ( .............

It's working but I don't know how to search a movie thanks to the button... do you know how can I do this ??

Thank you !

CodePudding user response:

Assuming your onClick is on the button it would be something like this, where you set the value of the movie as the value of the input field.

With your onChange set a value in the component for searchFieldValue and use it with the onClick. Ps your code is only html and JS as far as i can see, not a react related issue.

<button 
  className='search-button'
  onClick={(e) => {
     setSearchMovie(searchFieldValue);
  }}
>
  <AiOutlineSearch /> OK
</button>
  • Related