'How to implement Razorpay payment button in next.js page

Using the Razorpay payment button on the website is quite simple it gives a code like

<form>
<script 
  src = "https://cdn.razorpay.com/static/widget/payment-button.js"
  data-payment_button_id = "pl_FNmjTJSGXBYIfp"
  data-button_text = "Buy Now"
  data-button_theme = "brand-color">
</script>
</form>

But there's some problem when implementing this button on react.js Button is visible in inspector element but not visible in the screen.



Solution 1:[1]

As you may not know but the real problem lies on script tag inside component not executed after rendering that component. So now here I came with a solution for executing those script after rendering the component by using useEffect() from react.js to select that element and append script after first render.

useEffect(()=>{
  const Script = document.createElement("script");
  //id should be same as given to form element
  const Form = document.getElementById('donateForm');
  Script.setAttribute('src','your src')
  Script.setAttribute('data-payment_button_id','your id')
  Form.appendChild(Script);
},[])
. 
.
.
// form component
<form id='donateForm'> </form>

Some references I used which helped me searching the solution

https://github.com/utterance/utterances/issues/161

Adding script tag to React/JSX

Solution 2:[2]

useEffect(()=>{
async function makeForm() {
  const Script = document.createElement("script");
  const Form = document.getElementById('donateForm');
  Script.setAttribute('src','https://cdn.razorpay.com/static/widget/subscription-button.js')
  Script.setAttribute('data-subscription_button_id','pl_somethingsomething')
  Script.setAttribute('data-button_theme','brand-color')
  Form.appendChild(Script); 
}
makeForm()},[])

return(
<>
  <form id='donateForm'> </form>
</>

this code is working in .jsx page for

Solution 3:[3]

For integrating razorpay payment button on a nextjs site, the following code works.

  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);
  useEffect(() => {
    const Script = document.createElement("script");
    //id should be same as given to form element
    const Form = document.getElementById("donateForm");
    Script.setAttribute(
      "src",
      "https://checkout.razorpay.com/v1/payment-button.js"
    );
    Script.setAttribute("data-payment_button_id", "YOUR ID");
    if (Form) {
      Form.appendChild(Script);
    }
  }, [mounted]);


return mounted ? <form id="donateForm"></form> : null

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman
Solution 2
Solution 3