Skip to content

Instantly share code, notes, and snippets.

@aquiseb
Created August 19, 2020 16:06
Show Gist options
  • Save aquiseb/2362cfeaee004042d615c5111363f684 to your computer and use it in GitHub Desktop.
Save aquiseb/2362cfeaee004042d615c5111363f684 to your computer and use it in GitHub Desktop.

React + Ant modular prompt approach

This example shows how to trigger a simple prompt, but with a very modular approach.

/* eslint-disable react/prop-types */
import * as React from 'react';
import styled from 'styled-components';

import { Popconfirm as PopconfirmAnt, Button } from 'antd';

const Popconfirm = styled(PopconfirmAnt)`
	position: fixed;
	bottom: 0;
	right: 0;
`;

const Prompt = props => {
	const { children, ...rest } = props;
	return (
		<Popconfirm
			placement="topLeft"
			title={
				<div>
					<h1>Hello World!</h1>
				</div>
			}
			// onConfirm={confirm}
			okText="Yes"
			cancelText="No"
			{...rest}
		/>
	);
};

const Face = styled.div`
	position: fixed;
	width: 50px;
	height: 50px;
	background-color: red;
	bottom: 0;
	right: 0;
`;

const PromptContext = React.createContext();
const usePrompt = () => React.useContext(PromptContext);
const withPrompt = ComposedComponent => {
	const WithPrompt = () => {
		const [visible, setVisible] = React.useState(false);
		const togglePrompt = () => setVisible(!visible);
		return (
			<PromptContext.Provider value={{ togglePrompt, visiblePrompt: visible }}>
				<ComposedComponent />
				<Face>{visible ? 'HAPPY FACE' : 'NEUTRAL FACE'}</Face>
			</PromptContext.Provider>
		);
	};

	return WithPrompt;
};

const MyPage = () => {
	const { togglePrompt, visiblePrompt } = usePrompt();
	return (
		<>
			<h1>I am the page</h1>
			<Prompt visible={visiblePrompt} />
			<Button onClick={togglePrompt}>TL</Button>
		</>
	);
};

export default withPrompt(MyPage);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment