Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR TYPESCRIPT

Error: Objects are not valid as a React child (found: object with keys {counter}). If you meant to render a collection of children, use an array instead.

implemented a counter with increment, decrement and reset buttons and I was 
trying to display the count on to the screen but I was the above mentioned 
error.

In the code I had declared the count which is returned by useReducer hook as 
the object and I was directly trying to return it rather than the count 
property of it

I should actually return count.count and I was returning count only (object 
itself) not property.

We can stringify object and return the string also.

import React, { useReducer } from "react";

const initialState = {
count:0,
}
const reducer = (state, action) => {
    switch (action.type) {
        case 'increment':
            return {count:state.count + 1}
        case 'decrement':
            return {count:state.count - 1}
        case 'reset':
            return initialState
        default:
            return state
    }
}

function CounterWithReducer(props) {
  const [count, dispatch] = useReducer(reducer, initialState);

  return (
    <>
      <h1>{count}</h1>
      <button onClick={()=>{dispatch({type:'increment'})}}>Increment</button>

      <button onClick={()=>{dispatch({type:"decrement"})}}>Decrement</button>
      <button onClick={()=>{dispatch({type:"reset"})}}>Reset</button>
    </>
  );
}

export default CounterWithReducer;
In the above code {count} This section (in the return part ) is where I did the
mistake instead of count I need to use count.count

Summary is that if you trying to show object on to screen you can't either use 
JSON.stringify() or try to display any property of the object.
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #Objects #valid #React #child #object #keys #If #meant #render #collection #array
ADD COMMENT
Topic
Name
4+8 =