Kruton
Kruton

Reputation: 43

prompt(), but made in React

So lets say I have a PromptContainer somewhere in the tree. What I want to do is to "activate" it with customPrompt("title") function somewhere else in the app, much like react-toastify is working, but with the difference that the function would resolve to whatever user types in. What would be your approach? The only thing that comes to my mind would be to use redux or context api, but I think I didn't saw react-toastify use it?

Upvotes: 0

Views: 704

Answers (1)

Ron B.
Ron B.

Reputation: 1540

You can always use this library

However, if you want to implement it yourself, you can use the Context API a make yourself a custom hook called usePrompt or something. If you want to make it asynchronous, you can create a new Promise each time the prompt is triggered, save it resolve function in a ref (useRef) and when you click one of the options, call the resolve function.

I imagine it would be something along the lines of:

const PromptContext = React.createContext();

export function MyPropmptProvider (props) {
  const [message, setMessage] = useState('');
  const promptResolver = useRef(null);

  const prompt = promptMessage => {
     setMessage(promptMessage);
     return new Promise(resolve => promptResolver.current = resolve);
  }

  const selectOption = option => {
      promptResolver.current(option);
      setMessage('');
  }

  return (
     <PromptContext.Provider value={{prompt}}>
        // Your actual prompt component
        {props.children}
     </PromptContext.Provider>
  )
}

export const usePrompt = () => useContext(PromptContext);

Upvotes: 1

Related Questions