ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Friday, December 23, 2022

[FIXED] How do I call a component from another function?

 December 23, 2022     reactjs   

Issue

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;

Solution

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



Answered By - uzair
Answer Checked By - - Marilyn (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix