1

I'm trying to build a nav bar which would search for videos. The idea is extract an array of video titles and filter through to by using user's input from the search bar. The problem is that I cannot get the searchItem to persist. When redirected to /search searchItem is not part of the props. Any suggestions?

import React from "react";
import { Link } from 'react-router-dom';


class SearchBar extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            searchItem: ""
        };
        this.update = this.update.bind(this);
        this.handleSearch = this.handleSearch.bind(this);
    }

    update() {
        return e => this.setState({ searchItem: e.currentTarget.value });
    }

    handleSearch() {
        // debugger
        // e.preventDefault();
        console.log(this.state.searchItem)
        console.log(this.state)
        // this.props.location.search = this.searchItem;
    }

    render() {

        return (
            <div className="search-form">
                <form onSubmit={this.handleSearch()}>
                    <input type="text"
                        className="search-input"
                        placeholder="Search videos"
                        value={this.state.searchItem}
                        onChange={this.update()}
                    />
                    <button id="search-button">
                        <Link to="/search"><img id="search-icon" src="https://image.flaticon.com/icons/svg/49/49116.svg" alt="" /></Link>
                    </button>
                </form>
            </div>
        );
    }
}

export default SearchBar;
class Search extends React.Component {

    constructor(props) {
        super(props);
        console.log(this.props)
    }


    componentDidMount() {
        this.props.fetchVideos();
        this.props.fetchUsers();
    };

user13790968
  • 123
  • 8

1 Answers1

1

Search term are often persisted by adding them to the url as parameters such as mysite.com/search?search=foo. You could also use local storage or cookies, but these options would weaken browser navigation.

In your render function, set the <Link to={``/search?search=${this.state.searchItem}``} ...

Then, in the constructor, you get to choose how to get the query parameter from the url. The library querystring has tools to facilitate this, or you can write your own like this How to get the value from the GET parameters?. Once you have it, you can initialize the state with it.

Charlie Bamford
  • 1,268
  • 5
  • 18