Ekaji Onah
Ekaji Onah

Reputation: 55

Unable to setState on props in react functional component

I have been unable to setState on props I keep getting

TypeError: props.setState is not a function

I'm trying to implement a search function

const HeroComp = (props) => {
        let  handleSearchSubmit = (e) => {
          props.setState({searchValue: e.target.value});
      }
      return     <div className='heroComp' >
                <form action="" >
   
                <input type="text" placeholder='search cartigory'  onChange={handleSearchSubmit}   />
                 </form>
            </div>
}

export default HeroComp;

When I console.log(props) I get

{searchValue: ""}
searchValue: ""
__proto__: Object

This is the parent component

import images from '../data/images'; //the file from which i'm importing images data

class HomePage extends React.Component{
    constructor(){
        super();
        this.state = {
            images,
            searchValue: ''
        
    }
}

    render(){
        const {images , searchValue} = this.state;
        const filteredImage = images.filter(image => image.cartigory.toLowerCase().includes(searchValue));
            return(
                <div >
                    <HeroComp searchValue={ searchValue }  />
                    <GalleryComp filteredImage={filteredImage} />
                </div>
            )
        }

}

export default HomePage;

I know this should be easy but I just can't see the solution .

Upvotes: 1

Views: 1748

Answers (2)

Levitica
Levitica

Reputation: 56

How about this?

  useEffect(() => {
    // set the current state
    setSearchValue(props.searchValue)
  }, [props]);

Upvotes: 2

Jean Catarina
Jean Catarina

Reputation: 51

Functional component dont have state, but you can use reactHooks:

import React, { useState } from 'react';

const HeroComp = (props) => {
      let [searchValue, setSearchValue] = useState();

      let  handleSearchSubmit = (e) => {
          setSearchValue(e.target.value);
      }
      return     <div className='heroComp' >
                <form action="" >

                <input type="text" placeholder='search cartigory'  onChange={handleSearchSubmit}   />
                 </form>
            </div>
}


export default HeroComp;

Upvotes: 0

Related Questions