-2
var user = getCookie("usr_c");
   if (user != "" && user != undefined) {
       $("#user1").attr('src','https://youtube.com/?user='+user);
   }
    else{
       $("#user1").attr('src','https://youtube.com');
    }
<iframe custom-frame-section  frameborder="1" id="user1" style="border: 2px inset black; width: 285px; height: 400px;"></iframe>

Am trying this js code in my react component ,but getting error like $ is not defined,how to use the above code in React js

sai k
  • 13
  • 3
  • Do you have jquery? Did you import it anywhere? – razvans Mar 29 '21 at 19:38
  • no i have not imported import $ from jquery – sai k Mar 29 '21 at 19:41
  • what will be the alternative to $("#user1").attr('src','https://youtube.com/?user='+user); this code in react – sai k Mar 29 '21 at 20:10
  • If you really want to use jQuery (I would discourage using jQuery and in turn use straight React) then here is this answer: https://stackoverflow.com/a/41381583/9297141 – MsonC Mar 29 '21 at 21:52

1 Answers1

0

You can use react hooks.
I've modified your iframe component, Please have a look.

import { useRef, useEffect } from "react";

export default function IframeComponent() {
  const iframeRef = useRef(null);
  useEffect(function () {
    var user = Boolean(getCookie("usr_c"));
    iframeRef.current.src =
        user
        ? `https://youtube.com/?user=${user}`
        : "https://youtube.com";
  }, []);

  return <iframe title="youtube" frameBorder="1" ref={iframeRef} />;
}
Gaurav Mall
  • 500
  • 4
  • 16
  • Thanks a lot for helping.Code is working fine :) but i have small doubt as i canot install js-cookie ,what will be the alternative to use get cookie here ,i have var cookie = require('cookie');var name = cookie.name; I have used like this,but always user name is getting undefined. – sai k Mar 30 '21 at 04:01
  • I think that the package you are using `var cookie = require('cookie');` is node module. May be that's the reason it's not working. Anyways, Based on your scenario, you can use these packages https://www.npmjs.com/package/browser-cookies or https://www.npmjs.com/package/react-cookie. – Gaurav Mall Mar 30 '21 at 07:16