What is the process for importing an md file in a create-react-app project using JavaScript?

Attempting to execute the blog example provided on Material UI's getting started page. However, encountering an issue with the source code:

Inside blog.js

import post1 from './blog-post.1.md';

.
.
.
return( <Main>{post1}<Main/>);

and in Main.js:

import ReactMarkdown from 'markdown-to-jsx';
export default function Main(props) {
  
  return <ReactMarkdown options={options} {...props} />;
}

Upon running the code, receiving the following output:

/static/media/blog-post.1.0c315da1f0a7af641a3a.md
instead of the content within the MD file.

Desiring to achieve the same result, how can I import MD files in my create-react-app version? (excluding TypeScript)

Answer №1

To display the markdown content in a ReactMarkdown component, you first need to retrieve and load the markdown object. One common approach is to use the fetch method as an intermediary. Here's an example implementation:

import * as React from "react";
import ReactMarkdown from "markdown-to-jsx";
import post from "./post.md";

export default function MarkdownImport() {
  let [readable, setReadable] = React.useState({ md: "" });

  React.useEffect(() => {
    fetch(post)
      .then((res) => res.text())
      .then((md) => {
        setReadable({ md });
      });
  }, []);

  return (
    <div>
      <ReactMarkdown children={readable.md} />
    </div>
  );
}

Check out a working sample here: https://codesandbox.io/s/reactmarkdown-example-20vmg

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error occurred while attempting to upload a file using multipart form data: TypeError message displayed - Unable to access properties of undefined (specifically '0')

I am encountering an issue while trying to send multipart/form-data using axios from the frontend. The same post request works fine in Postman/Insomnia but fails when executed from the frontend. The backend shows the following error: node:events:505 ...

I am looking to export multiple 'Pure components'

Currently, I am developing an app using React Native and came across an unusual observation. For some reason, the following code throws an error unless I modify the last sentence to: export default MyButton3; I aim to export more than one pure component ...

What is the best way to verify a user's login status in AngularJS using $routeChangeStart event?

I am new to AngularJS and I need help checking if my user is logged in or not using $routeChangeStart. Controller angular.module('crud') .controller('SigninCtrl', function ($scope,$location,User,$http) { $scope.si ...

Placing a button above another element using CSS styled components

I'm attempting to make a button overlap and be positioned in a specific location on top of a search bar. The current appearance is not what I desire, as the button seems to shift back to its original position when adding a :hover element after applyin ...

Can you explain the functioning of knockout container less syntax? (does it have any drawbacks?)

There are numerous instances and examples of using knockout ContainerLess syntax, although I find it challenging to locate proper documentation from their site. Initially, my question was "is it evil?" but upon realizing my lack of understanding on how it ...

Unexpected output from Material UI Textfield

When attempting to print a page of my React app using window.print(), everything prints correctly except for the Textfield component from Material UI. It works fine when there are only a few lines of text, but when there is a lot of text, it appears like t ...

Prompt for confirmation in ASP.NET code-behind with conditions

I've searched around for a solution to this problem. Below is a representation of my pseudocode: bool hasData = ItemHasData(itemid); Confirm = "false"; // hidden variable if (hasData) { //Code to call confirm(message) returns "true" or "false" ...

The feature to hide columns in Vue-tables-2 seems to be malfunctioning

The issue I'm facing is with the hiddenColumns option not working as expected. Even when I set it to hiddenColumns:['name'], the name column remains visible. I've updated to the latest version, but the problem persists. UPDATE I am tr ...

Enhancing WordPress Menu Items with the 'data-hover' Attribute

Looking for a solution to add "data-hover" to menu items on Wordpress, like: Wanting to insert: data-hover="ABOUT US" into <a href="#">ABOUT US</a> without manually editing the link's HTML to make it: <a href="#" data-hover="ABOU ...

How can I best fill the HTML using React?

After attempting to follow various React tutorials, I utilized an API to fetch my data. Unfortunately, the method I used doesn't seem to be very efficient and the code examples I found didn't work for me. I am feeling quite lost on how to proper ...

Challenges with fading images using jQuery

I am currently working on animating a 5 image slideshow by creating a fading effect between the images rather than just switching abruptly. Here is my HTML structure: <div id="slides"> <ul class="pics"> <li><img src="imag ...

Sort an array using another array as the reference in JavaScript

I have encountered similar questions before, but my current challenge involves partially sorting an array based on values from another array. This is what I aim to achieve: let array = [ { name: "Foo", values: [a, b, c, d] }, { name: " ...

What is the reason behind Q.js promises becoming asynchronous once they have been resolved?

Upon encountering the following code snippet: var deferred = Q.defer(); deferred.resolve(); var a = deferred.promise.then(function() { console.log(1); }); console.log(2); I am puzzled as to why I am seeing 2, then 1 in the console. Although I ...

Using Node.js Express to serve a React build version

When I try to serve my react application with an Express server, I run into a problem. I have set up the react application to make API requests via a proxy, but now that I am serving the build using Node.js, all API routes are returning a 404 error. &quo ...

Guide to iterating within a loop with a variable number of iterations above or below the specified amount in JavaScript

I am currently engaged in a project for a small theater group, and I am facing challenges with getting this loop to execute properly. <% include ../partials/header %> <div class="jumbotron jumbotron-fluid"> <div class="container"> ...

Beginner - managing tasks with React and TypeScript

Can someone assist me with a minor issue? I have experience programming in React using pure JavaScript, but I'm struggling with transitioning to TypeScript. I don't quite understand all the hype around it and am finding it difficult to work with. ...

Chrome on OSX Mavericks threw a RangeError because the maximum call stack size was exceeded

While attempting to run an Angular app using linemanjs in Chrome on a Mac, I encountered the following error: Uncaught RangeError: Maximum call stack size exceeded An interesting observation is that the site functions properly on Chrome on a Windows mach ...

What is the solution for fixing scrolling while keeping the header fixed and ensuring that the widths of headers and cells are equal?

Is there a way to set a minimum width for headers in a table and provide a scroll option if the total width exceeds 100% of the table width? Additionally, how can we ensure that the width of the header and td elements are equal? Below is the HTML code: ht ...

The robot will automatically update its own message after a designated period of time

I am facing an issue with my code where the bot is not updating its message after a specific time period defined by time.milliseconds * 1000. How can I make the bot edit its message after that duration? let timeout = 15000; if (author !== null && ...

Having trouble with uploading an image in Laravel using a modal?

For my laravel inventory system, I am facing an issue with uploading images for products. The old code I used for image upload is not working in my current project where I am utilizing a modal and ajax request to save inputs in the database. Can anyone pro ...