How to read Github’s files(specially Markdown files) in React Project?



I want to read or embed Markdown files in my React Project? I just try following the code.

This Import Section:

import axios from "axios";
import marked from "marked";
import React, { useEffect, useState } from 'react';
import { Card, CardBody } from "reactstrap";

Then Here Constant and State:

 const url = 'https://github.com/shsohel/ERP/blob/main/ProjectTechnologiies.md';
 const [read, setRead] = useState( null );

Then I am using UseEffect to initial render and get the file from GitHub:

useEffect( () => {

    fetch( url )
        .then( response => {
            return response.text();
        } )
        .then( text => {
            setRead( {
                markdown: marked( text )
            } );
        } );
}, [] );

then Here html section:

return (
        <div>
            <Card>
                <CardBody dangerouslySetInnerHTML={{ __html: read?.markdown }}></CardBody>
            </Card>
        </div>
    );

But I have error in Console: 404 code error! How could I read the file from Github? Please Help me.

Answer

  1. Make sure you fetch the markdown as raw data and not just from the page. You can do this by clicking the Raw button in the top left on the file’s page.
  2. It seems you imported axios but then just used fetch. Make sure to decide on just one of them.

Here is a CodeSandbox the proposed changes.



Source: stackoverflow