Languages

React - JSX expressions must have one parent element error

3 points
Asked by:
Krzysiek
711

I tried to create a few buttons that change the state of a component, but I got this error:

(property) JSX.IntrinsicElements.button: 
  React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>
  JSX expressions must have one parent element.ts(2657)

My code: 

import React, { useState } from 'react'

const App = () => {
  const [sidebar, setSidebar] = useState( false );
  const clickHandler = () => {
    setSidebar(!sidebar);
  }
  return (
    <button onClick={clickHandler}>Show sidebar</button>
    <button >Logout</button>
  )
}

export default App;

 

1 answer
3 points
Answered by:
Krzysiek
711

To render multiple elements in React, you need to wrap them with a <div> because components can only return a single element.

However, there are situations when you may not want to create an additional element in the DOM, then you can use:

  • React fragments,
  • array notation.

Check this article to see how to return multiple elements from React component.

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join