anon
anon

Reputation:

onChange event on input returns 'Cannot read property search of undefined'

I have two React components, one parent component and one child component. They are both in a separate file and the code looks like this:

import React, { Component } from 'react';
import SearchBar from './SearchBar';
import axios from "axios/index";

var processedQuery;
var url = 'https://some-url-api.com/q=';

class MainContent extends Component {
    state = {
        results: '',
        query: ''
    }

    getData = () => {
        axios.get(url + processedQuery)
            .then(({ data }) => {
                this.setState({
                    results: data
                })
            })
    }

    handleInputChange = () => {
        processedQuery = this.search.value.split(' ').join('+');
        this.setState({
                query: processedQuery
            }, () => {
                this.getData();
            }
        )
    }

    render() {
        return (
            <div className="main-content">
                <SearchBar handleInputChange={this.handleInputChange} />
            </div>
        );
    }
}

export default MainContent;

And the child component:

import React, { Component } from 'react';

class SearchBar extends Component {
    render() {
        return (
            <div className="main-content__search-bar">
                <form>
                    <input
                        type="text"
                        placeholder="Search for..."
                        onChange={this.props.handleInputChange}
                    />
                </form>
            </div>
        );
    }
}

export default SearchBar;

Everything worked fine while the getData and handleInputChange functions were inside of the child component. However, when i moved them to the parent component and try to type something in the input, I get this error:

Uncaught TypeError: Cannot read property 'value' of undefined

I went through the code multiple times and can't really find what I'm missing. Any help?

Upvotes: 0

Views: 1831

Answers (1)

Frank Modica
Frank Modica

Reputation: 10516

Your parent component should take the new value as a parameter:

handleInputChange = (event) => {
    processedQuery = event.target.value.split(' ').join('+');
    // ...
}

I'd argue that the child should actually pass the value in (not the event).

onChange={event => this.props.handleInputChange(event.target.value)}

And the parent can do:

handleInputChange = (searchTerm) => {
    processedQuery = searchTerm.split(' ').join('+');
    // ...
}

Upvotes: 3

Related Questions