devDeejay
devDeejay

Reputation: 6019

Unable to pass function in props to a Component | React

I am trying to pass the function onSearchChangeEvent() from my App.js to Searchbox component as a function but I am getting the error saying

Expected onChange listener to be a function, instead got a value of object type.

I looked up to different answers on Stackoverflow for the same error but I am unable to resolve this issue.

App.js : Contains the function onSearchChangeEvent() I am trying to pass to a < Searchbox /> component.

import React, {Component} from 'react';
import Cardlist from './Cardlist';
import Searchbox from './Searchbox';
import {robots} from './robots';

class App extends Component {
    constructor () {
        super()
        this.state = {
            robots : robots,
            searchfield : ''
        }
    }

    onSearchChangeEvent = () => {
        console.log("Something Happened");
    }

    render () {
        return (
            <div className='tc'>
                <h1>Robo Friends</h1>
                <Searchbox searchChange={() => this.onSearchChangeEvent}/>     
                <Cardlist robots={this.state.robots} />
            </div>
        );
    }
}

export default App;

Searchbox.js

import React from 'react';

const Searchbox = (searchField, searchChange) => {
    return (
        <div className='pa2'>
            <input 
                className='pa3 ba b--green bg-lightest-blue'
                type='search' 
                placeholder='Search Robots'
                onChange={searchChange}
            />
        </div>
    );
}

export default Searchbox;

Error : First I get the warning, when the event is triggered I get the error

Upvotes: 1

Views: 1592

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281646

You aren't accessing the props correctly in SearchBox component. You would need to destructure them instead of defining them as arguments

const Searchbox = ({ searchField, searchChange }) => {
    return (
        <div className='pa2'>
            <input 
                className='pa3 ba b--green bg-lightest-blue'
                type='search' 
                placeholder='Search Robots'
                onChange={searchChange}
            />
        </div>
    );
}

and pass it down like

<Searchbox searchChange={this.onSearchChangeEvent}/>  

or

 <Searchbox searchChange={() => this.onSearchChangeEvent()}/>  

Though you must prefer <Searchbox searchChange={this.onSearchChangeEvent}/> since you are already using arrow function while defining onSearchChangeEvent function

Upvotes: 3

Related Questions