I am trying to set a state in a component and transfer that list from one component to another. But getting console error as List.map() is not a function!
I am trying to get webpage as enter image description here using react js
App.js :
import GoogleSuggestions from './components/GoogleSuggestions'
import './App.css'
const suggestionsList = [
{id: 1, suggestion: 'Price of Ethereum'},
{id: 2, suggestion: 'Oculus Quest 2 specs'},
{id: 3, suggestion: 'Tesla Share Price'},
{id: 4, suggestion: 'Price of Ethereum today'},
{id: 5, suggestion: 'Latest trends in AI'},
{id: 6, suggestion: 'Latest trends in ML'},
]
const App = () => <GoogleSuggestions suggestionsList={suggestionsList} />
export default App
components/GoogleSuggestions :
// Write your code here
import {Component} from 'react'
import SuggestionItem from '../SuggestionItem'
import './index.css'
class GoogleSuggestions extends Component {
state = {suggestionsList: this.props, searchInput: ''}
showoptions = event => {
this.setState({searchInput: event.target.value})
}
render() {
const {suggestionsList, searchInput} = this.state
console.log(typeof suggestionsList)
return (
<div className="bg-container">
<img
className="googleLogo"
src="https://assets.ccbp.in/frontend/react-js/google-logo.png"
alt="google logo"
/>
<div className="input-container">
<div>
<img
className="search-icon"
src="https://assets.ccbp.in/frontend/react-js/google-search-icon.png"
alt="search icon"
/>
<input
type="search"
value={searchInput}
onClick={this.showoptions}
className="input"
placeholder="Search Google"
/>
</div>
<ul className="ul-cont">
{suggestionsList.map(eachItem => (
<SuggestionItem itemDetails={eachItem} key={eachItem.id} />
))}
</ul>
</div>
</div>
)
}
}
export default GoogleSuggestions
SuggestionItem
// Write your code here
import {Component} from 'react'
import './index.css'
class SuggestionItem extends Component {
render() {
const {itemDetails} = this.props
const {id, suggestion} = itemDetails
return (
<li>
<div className="Item-cont">
<p>{suggestion}</p>
<img
src="https://assets.ccbp.in/frontend/react-js/diagonal-arrow-left-up.png"
alt="arrow"
/>
</div>
</li>
)
}
}
export default SuggestionItem
I am expecting to send list to component/GoogleSuggestions but getting as object.
2
Answers
You’re assigning your list incorrectly in your child component. It should be
this.props.suggestionsList
You are trying to assign all props to state instead of only
suggestionsList
.Also, you don’t need to put
suggestionsList
to state. It makes additional variable mutable and can lead to potential bugs. Just use it from props directly.Try this: