Misu Kuma
Misu Kuma

Reputation: 115

How do I call a component from another function?

I'm trying to create my own modal and I'd like to open it through calling a function, instead of putting the html directly. Is there a way to do that? Here's my code.

import { BiLink } from 'react-icons/bi';
import './ShareButton.css';

function ShareButton({postId}){

    function copyLinkOnClick() {
        const baseUrl = window.location.origin.toString();
        const urlToShare = baseUrl + '/post/' + postId;

        navigator.clipboard.writeText(urlToShare);
        //OPEN MODAL COMPONENT HERE.
    }

    return <div className="share-button-container">
        <BiLink className="share-button" onClick={copyLinkOnClick}/>
    </div>

}

export default ShareButton;

My modal component:

import './NuggetModal.css';

function NuggetModal({textBody}) {

    return <div className="nugget-container">
        {textBody} 
    </div>
}

export default NuggetModal;

Upvotes: 1

Views: 49

Answers (1)

uz.
uz.

Reputation: 51

You can use useState hook for this. Like create a state showModal and then set its value to true when you want to show the Modal otherwise set it to false. For instance

function ShareButton({postId}){
    // modal state
    const [showModal, setShowModal] = useState(false). 
    
    function copyLinkOnClick() {
        const baseUrl = window.location.origin.toString();
        const urlToShare = baseUrl + '/post/' + postId;

        navigator.clipboard.writeText(urlToShare);
        // set showModal to true in order to show Modal
        setShowModal(true)
    }

    return <div className="share-button-container">
        <BiLink className="share-button" onClick={copyLinkOnClick}/>
        {/* Modal will only be visible when showModal state is true */}
        {showModal && <NuggetModal handleClose={()=> setShowModal(false)}/>}
    </div>

}

and in NuggetModal component just call props.handleClose() function when you want to close the modal as it will set the ShareButton's showModal state to false

Upvotes: 1

Related Questions