Variable Passes down undefined to React child component

Viewed 26

I have a simple app which searches for a specific element in the Periodic Table and displays details about that element.

In my main component I have a search filter: the user searches the element by name and then the app displays the Single Element component which displays more information about it.

   import {useState, useEffect } from 'react'
import axios from 'axios'

const Elements = (elements, setElements, searchedElements) => {

  console.log(searchedElements)

if (searchedElements === undefined) {
  return null
}
if (searchedElements.length === 1) {
return (
  <div>
    <p>{searchedElements.atomicNumber}</p>
  </div>
)
}


}

const App = () =>  {
const [elements, setElements] = useState([])
const [newSearch, setNewSearch] = useState('')

const searchedElements = 
elements.filter(e => e.name.includes(newSearch))

console.log(searchedElements)

const handleChange = (event) => {
setNewSearch(event.target.value)
}

  useEffect(() => 
  {axios.get(`https://neelpatel05.pythonanywhere.com`)
  .then(response => {
    setElements(response.data)
  }).catch(error => {
    console.log(error);
})}, [elements])


  return (
    <div className="App">
      <h1>Element Reference App</h1>
<input onChange={handleChange} placeholder="Search element by name"></input>
<Elements elements={elements} searchedElements={searchedElements} />

    </div>
  );
}

export default App;

The variable "searchedElements" filters the user's search terms against all the elements.

when using console.log(searchedElements) in the App component - the correct information is displayed.

However, the console.log(searchedElements) in the component "Element" is undefined - despite the fact I have passed it down from the App component.

Can anyone elaborate as to why this is?

2 Answers

You are missusing function parameters. React components receive parameters as an object, that you can destructure like this:

const Elements = (props) => {
  const {elements, setElements, searchedElements} = props;
  ...
}

Plus, I think your useEffect has an infinite loop as you setElement() and watch for [element] dependency.

const Elements = ({searchedElements, elements, setElements}) => {

  console.log(searchedElements)

if (searchedElements === undefined) {
  return null
}
if (searchedElements.length === 1) {
return (
  <div>
    <p>{searchedElements[0].atomicNumber}</p>
  </div>
)
}


}

The answer is to either use props as in the answer above - or my answer which is simply putting curly braces where I'd forgotten to put them in the Element component

Related