Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Variable Passes down undefined to React child component

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading