React.js ライブラリ「react-modal」を使用してモーダルを実装する
- 作成日 2020.04.09
- 更新日 2022.04.09
- React
- react-modal, React.js, ライブラリ
ライブラリ「react-modal」をインストールすると、モーダルの実装が簡単に可能です。ここでは、react.jsでreact-modalを利用するための手順と簡単な使い方を記述してます。
環境
- OS CentOS Linux release 8.0.1905 (Core)
- node V12.13.1
- npm 6.14.1
- React 16.13.0
react.js環境構築
下記のコマンドで構築してます。ここでは、react-appという名前でプロジェクトを作成してます。
create-react-app react-app
react-modalインストール
作成したプロジェクトに移動して、インストールします。
※ここではbootstrapも使用するのでインストールしておきます。
## 作成したプロジェクトに移動
cd react-app
## インストール
npm install react-modal react-bootstrap
react-modal 使い方
srcディレクトリにsample.jsと名前で下記のコードを記述します。
import React from 'react';
import Modal from 'react-modal'
import 'bootstrap/dist/css/bootstrap.min.css'
import { Button } from 'react-bootstrap';
const customStyles = {
content : {
top : '50%',
left : '50%',
right : 'auto',
bottom : 'auto',
marginRight : '-50%',
transform : 'translate(-50%, -50%)'
}
};
const Sample = () => {
var subtitle;
const [modalIsOpen,setIsOpen] = React.useState(false);
function openModal() {
setIsOpen(true);
}
function afterOpenModal() {
subtitle.style.color = '#3ab60b';
}
function closeModal(){
setIsOpen(false);
}
return (
<div>
<Button variant="success" className="mr-2" onClick={openModal}>モーダル表示</Button>
<Modal
isOpen={modalIsOpen}
onAfterOpen={afterOpenModal}
onRequestClose={closeModal}
style={customStyles}
contentLabel="Example Modal"
>
<h2 ref={_subtitle => (subtitle = _subtitle)}>Mebee</h2>
<Button variant="success" className="mr-2" onClick={closeModal}>close</Button>
<div>テキストテキスト</div>
</Modal>
</div>
);
}
export default Sample;
次に、srcディレクトリ配下にあるApp.jsを下記のように編集します。
import React from 'react';
import Sample from './sample';
import './App.css';
function App() {
const style = {
width: "50%",
margin: "0 auto",
marginTop: 150
};
return (
<div className="App">
<div style={style}>
<Sample />
</div>
</div>
);
}
export default App;
実行します。
npm start
ブラウザから http://プライベートIP:3000にアクセスすると、モーダル機能が実装されていることが確認できます。
-
前の記事
mautic 日本語化の設定手順 2020.04.08
-
次の記事
React.js ライブラリ「interweave」を使用してHTMLを安全にレンダリングする 2020.04.09
コメントを書く