Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js Error: " Objects are not valid as a React child (found: object with keys {})."

I make a react.js app using the API "https://www.definitions.net/definitions_api.php". When I log data.result, it outputs the right array of results, but when I map through the state, I get this error: "Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead."

//states
  const [definition, setDefinition] = useState([])
  const [search, setSearch] = useState('')
  const [query, setQuery] = useState('')

  useEffect(() => {
    getDef()
   }, [query])


//FETCH
  const getDef = async () => {
  const response = await fetch(`....`)
  const data = await response.json()
  setDefinition(data.result);

//handle input
  const updateSearch = e => {
    setSearch(e.target.value)

  }

//get the final query onSubmit
const getQuery = e =>{
  e.preventDefault()
  setQuery(search)
  setSearch('')
}


 return (

  { definition && definition.map(item => (
       <Definition term={item.term} 
                  partofspeech = {item.partofspeech}
                  definition={item.definition} 
                  example = {item.example}                 
             />

            )
         )
        }

  );

in Definitions component I destructure the props:

function Definition({term, partofspeech, definition, example}) {
    return (
        <div className="definition">
            <h4>{term} ({partofspeech})</h4>
              <p>{definition}</p>
               <p>{example}</p>

        </div>
    )
}

Any help is welcome, thanks.

like image 214
maxianna Avatar asked Oct 18 '25 13:10

maxianna


1 Answers

Try this, when you loop the component loop the definition without the root element, it will cause error

const Component = () => {
  ....
  return (
    <Fragment>
      { definition && definition.map(item => (
       <Definition term={item.term} 
                  partofspeech = {item.partofspeech}
                  definition={item.definition} 
                  example = {item.example}                 
             />

            )
         )
        }

  )
    </Fragment>
  )
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
like image 190
Kaslie Avatar answered Oct 21 '25 03:10

Kaslie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!