1

Simple two component app. My idea that App.js has a simple counter. When I mount Demo1.js, it should display a simple header with counter value.

When I try to mount Demo1.js I receive an error "Uncaught Error: Objects are not valid as a React child (found: object with keys {props}). If you meant to render a collection of children, use an array instead."

I tried using Profiler for React components at Chrome DevTools, but I got stuck on message "Loading React Element Tree..."

// App.js
import React, { useState } from 'react';
import Demo1 from './Demo1';

function App() {

  const [counter, setCounter] = useState (0);
  const [Demo1visibility, setDemo1visibility]=useState(false);

  return (
    <div>
       <h1> Counter is {counter}</h1>
       <div>
          <button onClick={ previous => setCounter( count => count + 1)}> + </button>
          <button onClick={ previous => setCounter( count => count - 1)}> - </button>
       </div>
       <div>
          <button onClick={ previous => setDemo1visibility(true)}> show Demo1 component </button>
       </div>
       {Demo1visibility && <Demo1 props={counter}/>}

    </div>
  );
}

export default App;

// Demo1.js

import React from 'react';

function Demo1 (props) {
  return (
    <div>
      <h1> This is Demo1 component </h1>
      <h2> Props are {props} </h2>
    </div>
  );

}

export default Demo1;

I tried changing several times. Something wrong with my syntax?

  • 2
    Welcome to Stack Overflow! In what way is your code not working as expected? Please elaborate on the specific problem you are observing and what debugging you have done. To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources. – David May 25 '23 at 11:37
  • 2
    Does this answer your question? [Invariant Violation: Objects are not valid as a React child](https://stackoverflow.com/questions/33117449/invariant-violation-objects-are-not-valid-as-a-react-child) – David May 25 '23 at 11:40
  • 2
    Should be `function Demo1 ({ props }) {` – Konrad May 25 '23 at 12:14
  • 1
    I already gave you the answer – Konrad May 26 '23 at 07:52

1 Answers1

-1

I suggest to change the props name to counter:

{Demo1visibility && <Demo1 counter={counter}/>}

The problem is that props is an object. You should access the prop you want. Like this props.counter or props.props in your example.

// Demo1.js

import React from 'react';

function Demo1 (props) {
  return (
    <div>
      <h1> This is Demo1 component </h1>
      <h2> Props are {props.counter} </h2>
    </div>
  );

}

export default Demo1;

You can then choose to destructure the props object to have a cleaner code, check this.

Alì Shadman
  • 232
  • 1
  • 5