How to add Gihub Gist in React.js
author

Jon Snow

17 April 2023

How to add Gihub Gist in React.js


There are two methods for adding Github gist in React js

1. Using react-gist (NPM Package)

i. Install the react-gist package using npm

npm install react-gist

ii. In your React.js component, import the Gist component from the react-gist package

import React from 'react';
import Gist from 'react-gist';

iii. Use the Gist component in your React.js component by passing the id of the Gist as a prop:

function GistComponent() {
  return (
    <div>
      <Gist id="gist-id-here" />
    </div>
  );
}

export default GistComponent;

iv. Replace the gist-id-here with the actual ID of the Gist you want to embed



2. Using react-frame-component

Another Way to add a Github Gist to a React.js application is by using the react-frame-component package

i. Install the react-frame-component package using NPM

npm install react-frame-component

ii. In your React.js component, import the Frame component from the react-frame-component package

import React from 'react';
import Frame from 'react-frame-component';

iii. Add github gist link in gistUrl

function GistComponent() {
  const gistUrl = 'https://gist.github.com/your-username/your-gist-id.js';

  return (
    <div>
      <Frame
        style={{ width: '100%', height: '100%' }}
        initialContent={`<!DOCTYPE html><html><head></head><body><script src="${gistUrl}"></script></body></html>`}
      />
    </div>
  );
}

export default GistComponent;

Note: The react-frame-component package has some limitations such as not being able to access the parent DOM or CSS styles.

Solution

we want when someone click on anchor tag link open in new tab

import React from 'react';
import Frame from 'react-frame-component';

function GistComponent() {
  const gistUrl = 'https://gist.github.com/your-username/your-gist-id.js';

  const handleContentDidMount = (iframe) => {
    const anchors = iframe.contentWindow.document.getElementsByTagName('a');
    for (let i = 0; i < anchors.length; i++) {
      anchors[i].addEventListener('click', function (event) {
        event.preventDefault();
        window.open(this.href, '_blank');
      });
    }
  };

  return (
    <div>
      <Frame
        style={{ width: '100%', height: '100%' }}
        initialContent={`<!DOCTYPE html><html><head></head><body><script src="${gistUrl}"></script></body></html>`}
        contentDidMount={handleContentDidMount}
      />
    </div>
  );
}

export default GistComponent;

Thank You 🧡🧡


Share:  
https://www.democoding.in/blog...

Related Post

programming meme
Code Snippet

Codepen Ideas