Languages

React - JSX expressions must have one parent element error

3 points
Asked by:
Dirask JS Member
3640

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:
Dirask JS Member
3640

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
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