Reputation: 81
Problem Description: There is a button on a webpage, and when I click the button, there will be a popup containing an image. The button is in the file called "index.jsx", and clicking on the button will trigger a function in the file "popUp.js", which will pop a window up. So in essence, the button and the PopUp function are in separate files.
I want to write the function as:
export function PopUp (image: Image){
return{
...
};
}
which will have the same effect as https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal, except that the content of popup is an image rather than texts. I guess the emphasis of solution is on translating CSS on this webpage to react.js, but not sure how the syntax should look like.
Any idea on how I can implement this?
Upvotes: 3
Views: 34130
Reputation: 533
You can do it easily with react-modal. Here is an example, as a bonus I added closing modal when clicking on opened image. Image src and its description should be passed to popUp component as props in data object.
PopUp.js:
import React from 'react';
import Modal from 'react-modal';
import ModalButton from './modal-button';
import style from './style.css';
class PopUp extends React.Component {
constructor() {
super();
this.state = { modalOpened: false };
this.toggleModal = this.toggleModal.bind(this);
}
toggleModal() {
this.setState(prevState => ({ modalOpened: !prevState.modalOpened }));
}
render() {
const { data } = this.props;
return (
<div className={style.modalWrapper}>
<ModalButton handleClick={this.toggleModal}>
click to open modal
</ModalButton>
<Modal
className={{ base: [style.base]}}
overlayClassName={{ base: [style.overlayBase] }}
isOpen={this.state.modalOpened}
onRequestClose={this.toggleModal}
contentLabel="Modal with image"
>
<img
onClick={this.toggleModal}
src={data.src}
alt='image displayed in modal'
/>
<span className={style.text}>{data.description}</span>
</Modal>
</div>
);
}
}
export default PopUp;
And separated button, as you requested:
import React from 'react';
import style from './style.css';
const ModalButton = props => (
<button className={style.button} onClick={props.handleClick}>
{props.children}
</button>);
export default ModalButton;
Upvotes: 6