DEV Community

So Sun Park
So Sun Park

Posted on

Reviewing React Basic

1. element vs Component

Before: element format

  ReactDOM.render(<App />, appDOM)
const app = (
  <div>
    <Title>{counter}th cat meme</Title>
    <CatForm handleFormSubmit={handleFormSubmit} />
    <MainCard img="https://cataas.com/cat/595f280b557291a9750ebf65/says/JavaScript" />
    <Favorites />
  </div>
);

const appDOM = document.querySelector('#app');

ReactDOM.render(app, appDOM)
Enter fullscreen mode Exit fullscreen mode

After: Component format

  • If you want to add useState or functions inside app, it has to be changed from javascript element to React Component. This would frequently happen when you are changing codes to lift state up.

  • The last code should be changed like this : ReactDOM.render(<App />, appDOM)

If you write App only, like you're calling the name of element, not Component, this error message would pop up:

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.

const App = () {

  const [counter, setCounter] = React.useState(100);

  function handleFormSubmit() {
    // function
  }

  return(
    <div>
      <Title>{counter}th cat meme</Title>
      <CatForm handleFormSubmit={handleFormSubmit} />
      <MainCard img="https://cataas.com/cat/595f280b557291a9750ebf65/says/JavaScript" />
      <Favorites />
    </div>
  )
};

const appDOM = document.querySelector('#app');

ReactDOM.render(<App />, appDOM)
Enter fullscreen mode Exit fullscreen mode

2. Each child in a list should have a unique key prop.

Warning: Each child in a list should have a unique "key" prop.

Check the render method of Favorites. See https://reactjs.org/link/warning-keys for more information.
at CatItem (:70:45)
at Favorites
at div
at App (:99:31)

Before:

  <ul className="favorites">
    {
      cats.map(cat => <CatItem img={cat} />)
    }
  </ul>
Enter fullscreen mode Exit fullscreen mode

After:

  <ul className="favorites">
    {
      cats.map(cat => <CatItem img={cat} key={cat} />)
    }
  </ul>
Enter fullscreen mode Exit fullscreen mode

3. How to add a new item to a list that is created by useState

Use es6 Spread Operator

function Favorites() {
  const [favorites, setFavorites] = React.useState([CAT1, CAT2])

  function handleHeartClick() {
    console.log("Clicked Heart.");

    // add cat to the list
    setFavorites([...favorites, CAT3])
  }
}
Enter fullscreen mode Exit fullscreen mode

test repo: https://github.com/sosunnyproject/cat-meme-react

Top comments (0)