React + typescript how to pull 1 function within a React component

Asked

Viewed 58 times

2

export function BotaoMenuLink(props: Props) {

  return (
    <>

      <div className="">


        <a type="button" onClick={BotaoToggli} className="bg-blue-700 hover:bg-blue-800  h-10 w-10 rounded-full " >
          <div className="flex pt-3"></div>

        </a>
      </div>
    </>
  );
}

and this is the function

export function BotaoToggli(props: Props) {

  return (
    <>
    <div  className="px-2 pt-2 pb-4">
      <a  className="block px-2 py-1 text-white font-semibold rounded hover:bg-gray-800">List your property</a>
      <a  className="mt-1 block px-2 py-1 text-white font-semibold rounded hover:bg-gray-800">Trips</a>
      <a  className="mt-1 block px-2 py-1 text-white font-semibold rounded hover:bg-gray-800">Messages</a>
    </div>
    </>
  );
}

I would like - briefly - to call div below by clicking on div from above. Similar to Toggle, but, I don’t know how to do this function in type Script, only html in React. These are components of the React I’m learning to do. Tips on how to improve this component are welcome.Similar to this image.

inserir a descrição da imagem aqui

  • Your question is unclear, but I noticed that you put a functional component as the onClick of an anchor. You want the BotaoToggli every time you click the anchor?

  • I’m sorry Rafael, but I just edited the post and it includes an image. Yes, similar to show() Hide() function that in java Script I know how to do, but in React no.

1 answer

3


You will have to use the useState hook for this, in order to have a variable state within a functional component, then you change this bit variable and show or not show the component, follow example:

import React, {useState} from 'react'
import BotaoToggli from '...../BotaoToggli'

export function BotaoMenuLink(props: Props) {
    const [togg, setTogg] = useState(false);
    return (
        <>
            <div className="">
                <a type="button" onClick={() => setTogg(!togg)} 
                    className="bg-blue-700 hover:bg-blue-800  h-10 w-10 rounded-full"
                >
                    <div className="flex pt-3"></div>
                </a>
            {
                togg ? <BotaoToggli /> : null
            }       
      </div>
    </>
  );
}
  • Thank you so much for your support, you helped me so much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.