Dynamically loading Markdown file in React - reactjs

I use markdown-to-jsx to render markdown in my React component.
My problem is that I want to dynamically load the markdown file, instead of specifying it with import. The scenario is that this happens on an article details page, i.e. I get the articleId from the route params and then based on that id, I want to load the corresponding markdown file, e.g. article-123.md.
Here's what I have so far. How can I load the md file dynamically?
import React, { Component } from 'react'
import Markdown from 'markdown-to-jsx';
import articleMd from './article-123.md'
class Article extends Component {
constructor(props) {
super(props)
this.state = { md: '' }
}
componentWillMount() {
fetch(articleMd)
.then((res) => res.text())
.then((md) => {
this.setState({ md })
})
}
render() {
return (
<div className="article">
<Markdown children={this.state.md}/>
</div>
)
}
}
export default Article
This works fine as is, but if I remove import articleMd from './article-123.md' at the top and instead pass the file path directly to fetch it output what looks like index.html, not the expected md file.

Can't you use dynamic import?
class Article extends React.Component {
constructor(props) {
super(props)
this.state = { md: '' }
}
async componentDidMount() {
const articleId = this.props.params.articleId; // or however you get your articleId
const file = await import(`./article-${articleId}.md`);
const response = await fetch(file.default);
const text = await response.text();
this.setState({
md: text
})
}
render() {
return (
<div className="article">
<Markdown children={this.state.md} />
</div>
)
}
}

I know this is an old thread but I just solved this issue with the following code
using markdown-to-jsx
import React, { Component } from 'react'
import Markdown from 'markdown-to-jsx'
class Markdown_parser extends Component {
constructor(props) {
super(props)
this.state = { md: "" }
}
componentWillMount() {
const { path } = this.props;
import(`${path}`).then((module)=>
fetch(module.default)
.then((res) => res.text())
.then((md) => {
this.setState({ md })
})
)
}
render() {
let { md } = this.state
return (
<div className="post">
<Markdown children={md} />
</div>
)
}
}
export default Markdown_parser
I then call the class sa follows
<Markdown_parser path = "path-to-your-fle" />

Related

Child component not triggering rendering when parent injects props with differnt values

Here are my components:
App component:
import logo from './logo.svg';
import {Component} from 'react';
import './App.css';
import {MonsterCardList} from './components/monster-list/monster-card-list.component'
import {Search} from './components/search/search.component'
class App extends Component
{
constructor()
{
super();
this.state = {searchText:""}
}
render()
{
console.log("repainting App component");
return (
<div className="App">
<main>
<h1 className="app-title">Monster List</h1>
<Search callback={this._searchChanged}></Search>
<MonsterCardList filter={this.state.searchText}></MonsterCardList>
</main>
</div>
);
}
_searchChanged(newText)
{
console.log("Setting state. new text: "+newText);
this.setState({searchText:newText}, () => console.log(this.state));
}
}
export default App;
Card List component:
export class MonsterCardList extends Component
{
constructor(props)
{
super(props);
this.state = {data:[]};
}
componentDidMount()
{
console.log("Component mounted");
this._loadData();
}
_loadData(monsterCardCount)
{
fetch("https://jsonplaceholder.typicode.com/users", {
method: 'GET',
}).then( response =>{
if(response.ok)
{
console.log(response.status);
response.json().then(data => {
let convertedData = data.map( ( el, index) => {
return {url:`https://robohash.org/${index}.png?size=100x100`, name:el.name, email:el.email}
});
console.log(convertedData);
this.setState({data:convertedData});
});
}
else
console.log("Error: "+response.status+" -> "+response.statusText);
/*let data = response.json().value;
*/
}).catch(e => {
console.log("Error: "+e);
});
}
render()
{
console.log("filter:" + this.props.filter);
return (
<div className="monster-card-list">
{this.state.data.map((element,index) => {
if(!this.props.filter || element.email.includes(this.props.filter))
return <MonsterCard cardData={element} key={index}></MonsterCard>;
})}
</div>
);
}
}
Card component:
import {Component} from "react"
import './monster-card.component.css'
export class MonsterCard extends Component
{
constructor(props)
{
super(props);
}
render()
{
return (
<div className="monster-card">
<img className="monster-card-img" src={this.props.cardData.url}></img>
<h3 className="monster-card-name">{this.props.cardData.name}</h3>
<h3 className="monster-card-email">{this.props.cardData.email}</h3>
</div>
);
}
}
Search component:
import {Component} from "react"
export class Search extends Component
{
_searchChangedCallback = null;
constructor(props)
{
super();
this._searchChangedCallback = props.callback;
}
render()
{
return (
<input type="search" onChange={e=>this._searchChangedCallback(e.target.value)} placeholder="Search monsters"></input>
);
}
}
The problem is that I see how the text typed in the input flows to the App component correctly and the callback is called but, when the state is changed in the _searchChanged, the MonsterCardList seems not to re-render.
I saw you are using state filter in MonsterCardList component: filter:this.props.searchText.But you only pass a prop filter (filter={this.state.searchText}) in this component. So props searchTextis undefined.
I saw you don't need to use state filter. Replace this.state.filter by this.props.filter
_loadData will get called only once when the component is mounted for the first time in below code,
componentDidMount()
{
console.log("Component mounted");
this._loadData();
}
when you set state inside the constructor means it also sets this.state.filter for once. And state does not change when searchText props change and due to that no rerendering.
constructor(props)
{
super(props);
this.state = {data:[], filter:this.props.searchText};
}
If you need to rerender when props changes, use componentDidUpdate lifecycle hook
componentDidUpdate(prevProps)
{
if (this.props.searchText !== prevProps.searchText)
{
this._loadData();
}
}
Well, in the end I found what was happening. It wasn't a react related problem but a javascript one and it was related to this not been bound to App class inside the _searchChanged function.
I we bind it like this in the constructor:
this._searchChanged = this._searchChanged.bind(this);
or we just use and arrow function:
_searchChanged = (newText) =>
{
console.log("Setting state. new text: "+newText);
this.setState({filter:newText}, () => console.log(this.state));
}
Everything works as expected.

React, How to use a menu in a seperate file to call an api and return data to a different section of the main file

I have a react app with a large menu, and as such am trying to move it to a seperate file from the main app.js
at the mement when you click on a link in the menu it call a node api and which returns some data, however when I try to seperate I can not get it to populate the results section which is still in the main script
Working version app.js
import React,{ useState } from 'react';
import './App.css';
import axios from 'axios';
import { Navigation } from "react-minimal-side-navigation";
import "react-minimal-side-navigation/lib/ReactMinimalSideNavigation.css";
export default class MyList extends React.Component {
constructor(props) {
super(props);
this.state = {
result: [],
};
this.callmyapi = this.callmyapi.bind(this);
}
render() {
return (
<div>
<div class="menu">
<Navigation
onSelect={({itemId}) => {
axios.get(`/api/menu/`, {
params: {
Menu: itemId,
}
})
.then(res => {
const results = res.data;
this.setState({ results });
})
.catch((err) => {
console.log(err);
})
}}
items={[
{
title: 'Pizza',
itemId: '/menu/Pizza/',
},
{
title: 'Cheese',
itemId: '/menu/cheese',
}
]}
/>
</div>
<div class="body">
this.state.results && this.state.results.map(results => <li>* {results.Name}</li>);
</div>
</div>
);
}
}
New app.js
import React,{ useState } from 'react';
import './App.css';
//import axios from 'axios';
//import { Navigation } from "react-minimal-side-navigation";
//import "react-minimal-side-navigation/lib/ReactMinimalSideNavigation.css";
import MyMenu from './mymenu';
export default class MyList extends React.Component {
constructor(props) {
super(props);
this.state = {
result: [],
};
this.callmyapi = this.callmyapi.bind(this);
}
render() {
return (
<div>
<div class="menu">
<MyMenu />
</div>
<div class="body">
this.state.results && this.state.results.map(results => <li>* {results.Name}</li>);
</div>
</div>
);
}
}
New menu file
mymenu.js
import React, { Component } from 'react';
import axios from 'axios';
import './App.css';
//import MyList from './App.js';
//import { ProSidebar, Menu, MenuItem, SubMenu } from 'react-pro-sidebar';
//import 'react-pro-sidebar/dist/css/styles.css';
import { Navigation } from "react-minimal-side-navigation";
//import Icon from "awesome-react-icons";
import "react-minimal-side-navigation/lib/ReactMinimalSideNavigation.css";
//export default async function MyMenu(){
export default class MyMenu extends React.Component {
constructor(props) {
super(props);
};
render() {
return (
<div>
<Navigation
// you can use your own router's api to get pathname
activeItemId="/management/members"
onSelect={({itemId}) => {
// return axios
axios.get(`/api/menu/`, {
params: {
// Menu: itemId,
Menu: "meat",
SubMenu : "burgers"
}
})
.then(res => {
const results = res.data;
this.setState({ results });
})
.catch((err) => {
console.log(err);
})
}}
items={[
{
title: 'Pizza',
itemId: '/menu/Pizza/',
},
{
title: 'Cheese',
itemId: '/menu/cheese',
}
]}
/>
</div>
);
}
}
Any help would be greatly appreciated
That one is quite easy once you understand state. State is component specific it that case. this.state refers to you App-Component and your Menu-Component individually. So in order for them to share one state you have to pass it down the component tree like this.
export default class MyList extends React.Component {
constructor(props) {
super(props);
this.state = {
result: [],
};
}
render() {
return (
<div>
<div class="menu">
<MyMenu handleStateChange={(results: any[]) => this.setState(results)} />
</div>
<div class="body">
this.state.results && this.state.results.map(results => <li>* {results.Name}</li>);
</div>
</div>
);
}
}
See this line: <MyMenu handleStateChange={(results: any[]) => this.setState(results)} />
There you pass a function to mutate the state of App-Component down to a the child
There you can call:
onSelect={({itemId}) => {
// return axios
axios.get(`/api/menu/`, {
params: {
// Menu: itemId,
Menu: "meat",
SubMenu : "burgers"
}
})
.then(res => {
const results = res.data;
this.props.handleStateChange(results)
})
.catch((err) => {
console.log(err);
})
You mutate the parent state and the correct data is being rendered. Make sure to practice state and how it works and how usefull patterns look like to share state between components.
Thanks - I Have found solution (also deleted link question)
above render added function
handleCallback = (results) =>{
this.setState({data: results})
}
then where I display the menu
<MyMenu parentCallback = {this.handleCallback}/>
where i display the results
{this.state.results && this.state.results.map(results => <li>{results.Name}</li>}
No aditional changes to the menu scripts

Can't loop through array using map loop with react.js & axios

I am fetching data from an API, i get all the data in the console.log(this.state.reviews) but i can't access the data after the map loop is done.
The Brand data is accessible, the only problem is with the map loop (the reviews array)
I know it has something with async calls! i have found this Can't access values for Axios calls in map loop Does anyone know how to adapt it with the code below ;-)
class App extends React.Component {
constructor(props){
super(props);
this.state = {
reviews : []
};
}
componentDidMount() {
axios.get(`https://api.prime.com/businesses/reviews/${this.props.BrandId}`)
.then((res) => {
const brand = res.data;
this.setState({
// Reviews data
reviews : brand.reviews.items,
// Brand data
logo : brand.business.logo,
name : brand.business.name,
voters : brand.business.voters,
url : brand.business.url
});
})
}
render() {
console.log(this.state.reviews);
return (
<div className="widget-wrapper">
<OwlCarousel className="reviews-container"
loop
nav
margin={12}
dots={false}
items={5}
autoplay={true}
>
{this.state.reviews.map((review) => {
<div key={review.id} className="review-item">
<a href={this.state.url + '/' + review.slug} target="_blank" rel="nofollow">
<div className="review-heading">{review.subject}</div>
<div className="review-content">{review.message}</div>
</a>
</div>
})}
</OwlCarousel>
</div>
)
}
}
i figured out your problem you need to wait for the promise to resolve that why your state is not set for doing this u can use async await like
import React from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import "./styles.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
}
componentDidMount() {
this.loadData();
}
loadData = async () => {
const res = await axios.get("https://jsonplaceholder.typicode.com/posts");
if (res) {
const posts = res.data;
this.setState({
posts: [...posts]
});
}
};
renderPost = () => {
return this.state.posts
? this.state.posts.map(data => (
<div style={{ color: "black" }}>
<h5>{data.title}</h5>
<p>{data.body}</p>
</div>
))
: "loading...";
};
render() {
console.log(this.state.posts);
return <div> {this.renderPost()}</div>;
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
full app is here check it out : codesandbox

Updating video element src with different streams via blob URL

My react component 'VideoPlayer' doesn't update its src attribute as its props change.
Each time getUrlStreamForMostRecentMP4OnDb() is called a new blob Url object is created. This object streams the most recent video added to the database. No matter what the latest video on the database is the video element always renders the same initial video.
App.js
import React, { Component } from "react";
import VideoPlayer from "./VideoPlayer";
export default class App extends Component {
constructor(props, context) {
super(props, context);
this.getUrlStreamForMostRecentMP4OnDb = this.getUrlStreamForMostRecentMP4OnDb.bind(
this
);
this.state = {
playerSource: null,
};
}
async getUrlStreamForMostRecentMP4OnDb() {
fetch("http://localhost:4000/ytdl/streamMP4")
.then(re => re.blob())
.then(blob => URL.createObjectURL(blob))
.then(url => {
this.setState({ playerSource: url });
})
.catch(err => {
console.log(err);
});
}
render() {
return (
<div>
<button onClick={this.getUrlStreamForMostRecentMP4OnDb}>
Get url stream for most recent mp4 from db.
</button>
{this.state.playerSource ? (
<VideoPlayer
key={this.state.playerSource}
playerSource={this.state.playerSource}
/>
) : (
<div />
)}
</div>
);
}
}
VideoPlayer.js
import React, { Component } from "react";
export default class VideoPlayer extends Component {
constructor(props, context) {
super(props, context);
}
render() {
return (
<div>
<video
id="video"
width={300}
ref="player"
muted={true}
autoPlay={true}
loop
crossOrigin="anonymous"
src={this.props.playerSource}
>
</video>
</div>
);
}
}
I know this is an old question, but I got it to work by manipulating the dom directly like this:
const onUpload = ({ event, ContentId, ContentIndex }) => {
if (event.target.files.length) {
var UploadedVideo = event.target.files[0];
var MediaUrl = URL.createObjectURL(UploadedVideo);
var VideoElement = document.getElementById(`video_${ContentId}`);
if (VideoElement) {
VideoElement.src = MediaUrl;
VideoElement.load();
}
}
}

Undefined props in componentDidMount

This is starting to get really frustrating. Basically, I cannot access props in my subcomponents. if I try to render them directly using this.props- it works, but if I need to do additional processes with them, or save them into state, I get undefined props all the time. I have a parent component, which looks something like this:
import React from 'react';
import Title from './EventSubComponents/Title';
import SessionInfo from './EventSubComponents/SessionInfo';
import SessionTime from './EventSubComponents/SessionTime';
import Location from './EventSubComponents/Location';
import Subscribers from './EventSubComponents/Subscribers';
class EventNode extends React.Component {
constructor(props) {
super(props);
this.state = {
'event': [],
}
}
componentDidMount() {
this.getEvent(this.props.location.selectedEventId);
}
getEvent(eventId) {
fetch('/api/v.1.0/event/' + eventId, {mode: 'no-cors'})
.then(function(response) {
if(!response.ok) {
console.log('Failed to get single event.');
return;
}
return response.json();
})
.then((data) => {
if (!data) {
return;
}
this.setState({
'event': data
})
});
}
render() {
return(
<div className="event-wrapper">
<Title
title = { this.state.event.title }
date = { this.state.event.start }
/>
<SessionInfo
distance = { this.state.event.distance }
type = { this.state.event.type }
/>
<SessionTime
start = { this.state.event.start }
end = { this.state.event.end }
/>
<Location location = { this.state.event.start_location }/>
<Subscribers
subscribers = { this.state.event.subscribers }
eventId = { this.state.event._id }
/>
</div>
);
}
}
export default EventNode;
And my sub-component SessionTime, which looks like this:
import React from 'react';
import moment from 'moment';
class Title extends React.Component {
constructor(props) {
super(props);
this.state = {
'title': '',
'date': '',
}
}
componentDidMount() {
console.log(this.props.title);
console.log(this.props.date);
// undefined both props.
this.convertToTitleDate(this.props.date);
this.setState({
'title': this.props.title
})
}
convertToTitleDate(date) {
var newDate = moment(date).format('dddd, Do MMMM')
this.setState({
'date': newDate,
});
}
render() {
return (
<div className="event-title-wrapper">
<h1> { this.state.title } </h1>
<div className="event-title-date"> { this.state.date } </div>
</div>
);
}
}
export default Title;
Could anyone explain, why both this.props.date and this.props.title are undefined in my componentDidMount function? I have couple more components in my EventNode and I have the same problems in them as well.
Changing componentDidMount to componentWillMount does not help. I am fairly certain I have problems in my parent EventNode component, but I cannot figure out where. Inside EventNode render() all the state variables are defined.
You initialize event to an empty array and pass down this.state.event.start and this.state.event.end to SessionTime, which will both be undefined on first render since event has not been loaded yet and there are no start and end properties on the array.
You could instead e.g. set event to null initially, and return null from the render method until the event has been loaded.
Example
class EventNode extends React.Component {
state = {
event: null
};
// ...
render() {
const { event } = this.state;
if (event === null) {
return null;
}
return (
<div className="event-wrapper">
<Title title={event.title} date={event.start} />
<SessionInfo distance={event.distance} type={event.type} />
<SessionTime start={event.start} end={event.end} />
<Location location={event.start_location} />
<Subscribers
subscribers={event.subscribers}
eventId={this.state.event._id}
/>
</div>
);
}
}

Resources