Home > Software engineering >  How can I return Multiple returns in react/JS
How can I return Multiple returns in react/JS

Time:04-27

I am wondering how I would be able to return multiple returns from a single return in react/JS. I know technically this is not right and you really should put it into a return object but I am looking for the best syntax in doing so.

I want to return both my div and also the value of my state outside my div.

The state here is myselectedcatagory. Separately, I also want to output my h1 value hello.

The reason I am doing it like this is I would like to deconstruct my state value out of my function later on down the line in another JS file.

     return (
        myselectedcatagory,
        (
<div>
            <h1> Hello</h2>
<div/>
          )}

CodePudding user response:

Just wrap them into another element. If you do not just print and you need it in a higher level component, create the state in the higher level component and just update the state with a function passed as a prop.

<>
  {myselectedcatagory}
  <div>
    <h1>Hello</h2>
  <div/>
</>

CodePudding user response:

if you want to return both state and elements from a component, just convert the component to a hook

function useMyHookThatReturnsAStateAndAnElement() {
  const myselectedcatagory = 'this is some state'
  const myElement = (
    <div>
      <h1>Hello</h2>
    <div/>
  )

  return [
    myselectedcatagory,
    myElement
  ]
}

function SomeComponent() {
  const [myselectedcatagory, myElement] = useMyHookThatReturnsAStateAndAnElement()

  return (
    <div>
      my state is: {myselectedcatagory}
      and
      my element is: {myElement}
    </div>
  )
}
  • Related