Md. Ali Rabbi
Md. Ali Rabbi

Reputation: 19

Reactjs - TypeError: Cannot read property 'map' of undefined (in funtional component)

I am doing a simple react app that can find images from an API call. But there is a showing this problem. In imageList.js I got this error.please help me for below error TypeError: Cannot read property 'map' of undefined i don't know how to solve i am new for react pease help me for this code

App.js

import React from 'react';
import SearchBar from './SearchBar'
import unsplash from '../api/unsplash';
import ImageList from './imageList'

class App extends React.Component{
    state = {images : []}
   onSearchSubmit = async  (term) => {
       const response = await unsplash.get('/search/photos',{
            params : {query : term}
          })
        // .then ((response)=>{
            // console.log(response.data.results)

        // })
        this.setState({images : response.data.results});
            
        
    }
     
    render(){
       return(
           <div className='ui container' style={{marginTop : '10px'}}>
            <SearchBar onSubmit={this.onSearchSubmit} />
            <ImageList image = {this.state.images} />
        </div>
       );
    }
}
export default App;

SearchBar.js

import React from 'react';


class SearchBar extends React.Component{
   
    state = { term : ''}

    onSubmitForm = (event) => {
        event.preventDefault();
        this.props.onSubmit(this.state.term)
    }


    render(){
        return(
            <div className='ui segment'>
                <form onSubmit = {this.onSubmitForm} className = 'ui form'>
                    <div className= 'field'>
                        <label>Image Search</label>
                       <input type= 'text' 
                       value = {this.state.term}
                       onChange={(e)=>this.setState({term: e.target.value})} />
                    </div>
                </form>
            </div>
        )
    }
}

export default SearchBar;

imageList.js

import React from 'react';

const ImageList = (props)=>{
    
    const images = props.images.map(({description,id,urls})=>{
        return <img alt={description} key = {id} src= {urls.regular} /> ;
    });
    return(
        <div>{images}</div>
    )

};
export default ImageList

Upvotes: 0

Views: 41

Answers (1)

Christian
Christian

Reputation: 1798

Your prop is called image but in the component, you are accessing it via props.images. Change these to be the same.

<ImageList image={this.state.images} />
// Should be
<ImageList images={this.state.images} />

Upvotes: 3

Related Questions