How to render a foo.md markdown file in react? - reactjs

I have several .md files (containing long texts) and I want to render them through react. I tried to use markedown-it but the loader returns an error. Here is the webpack.config.js file:
var path = require('path');
var webpack = require('webpack');
var subscript = require('markdown-it');
var superscript = require('markdown-it');
module.exports = {
entry: ['./src/first.jsx'],
devtool: 'cheap-module-eval-source-map',
output: { path: __dirname+"/app", filename: 'bundle.js' },
module: {
loaders: [
{ test: /\.jsx?$/,
loader: 'babel-loader',
query: { presets: ['es2015', 'react'] },
include: path.join(__dirname, 'src')
},
{ test: /\.md/,
loader: 'markdown-it'
}
]
},
'markdown-it': {
preset: 'default',
typographer: true,
use: [subscript, superscript]
}
};
Is there something wrong with that file? How else I can add my *.md files to react?
After reading http://www.shoutinginfrench.com/today-i-made-react-load-markdown/ I tried to use markdown-loader. Following that, I added this to webpack.config file:
{ test: /\.md$/,
loader: "html!markdown"
}
which worked with no problem. Then I tried to add the markdown file to the react component as follow:
import React from 'react';
import { Link } from 'react-router'
import markdownFile from './test-file.md';
export const Test = React.createClass({
rawMarkup(){
return { __html: markdownFile };
},
render() {
return (
<div className="something">
<div className="row">
<div className="col-10">
<div dangerouslySetInnerHtml={this.rawMarkup()} />
</div>
</div>
</div>
);
}
});
But I'm getting the following error:
ERROR in ./src/components/tst.jsx
Module not found: Error: Cannot resolve module 'html' in /Users/..../src/components
# ./src/components/tst.jsx 14:15-39
How can I fix it?!

add { test: /\.md$/, loader: "html!markdown" },{ test: /\.json$/, loader: "json" } to your webpack.config.js .
npm install react-markdown --save-dev

Related

Can't render an img with react and webpack

Hi guys I'm new to Webpack so I'm having some problems when trying to add the src of an img tag because I'm getting an error, I already tried some solutions that I saw in other similar questions like adding the url-loader but I still can't get it to work
I'm getting this error in my code
ERROR in ./client/src/img/logo.png 1:0
[0] Module parse failed: Unexpected character '�' (1:0)
[0] You may need an appropriate loader to handle this file type, currently no loaders are
configured to process this file. See https://webpack.js.org/concepts#loaders
[0] (Source code omitted for this binary file)
[0] # ./client/src/pages/Homepage.js 108:9-35
[0] # ./client/src/App.js 3:0-40 9:38-46
[0] # ./client/src/index.js 3:0-24 4:50-53
My Webpack.config.js code
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
main: path.join(__dirname, 'client/src/index.js')
},
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js'
},
plugins: [new HtmlWebpackPlugin({
title: 'Ig Scraper',
template: path.join(__dirname, 'client/templates/index.ejs'),
filename: 'index.html'
})],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|express)/,
use: {
loader: 'babel-loader',
options: {
presets: [
"#babel/preset-env",
"#babel/preset-react"
]
},
}
},
{
test: /\.(html)$/,
use: {
loader: 'html-loader',
options: {
attrs: [':data-src']
}
}
},
// {
// test: /\.(png|jpg)$/,
// include: path.join(__dirname, '/client/img'),
// loader: 'file-loader'
// },
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
use: [
{
loader: 'url-loader?limit=100000'
}
]
}
]
},
devServer: {},
resolve: {
extensions: ["*", ".js", ".jsx"]
},
resolveLoader: {
extensions: ["babel-loader"]
},
devtool: 'source-map',
mode: 'development',
resolve: {
fallback: {
fs: false
}
}
};
My Homepage.js code
import React, { useState } from "react";
import axios from "axios";
import '../assets/Homepage.css'
// import logo from '../img/instagramLogo.png'
const Homepage = () => {
return (
<>
<div className="container">
<div className="homepage">
<div className="homepage__igAssets">
<img src={require('../img/logo.png')} alt="" className="ig__logo" />
{/* <img src="./assets/instagram.png" alt="" className="ig__text" /> */}
</div>
<h1 className="homepage__title">¡Let's scrape your instagram account! </h1>
<div className="homepage__elements">
<input className="homepage__input" placeholder="Username..." value= {username} onChange={onChange} />
<button className="homepage__button" onClick={onClick}>Get instagram followers!</button>
</div>
{renderData()}
</div>
</div>
</>
);
};
export default Homepage;
My files organization
Most likely, this error comes from Homepage.js, on the line:
<img src={require('../img/logo.png')} ... />
Require is not meant for images, but for js modules (learn more here).
Erratum: Above is about require in nodejs, it may not be the way to go, but require seems to work fine with webpack.
The way to use images with react would be:
// First, import the image file
import image from './path-to-image.png';
// Later, use it as source in the render
<img src={image} ... />
Your webpack.config.js looks fine (although i'm no expert at such things).
Add: Here is an other question highly related that might help you

cannot use the image inside the storybook

I tried to use the images in the storybook. that image also inside the storybook project only.
Here is my storybook webpack.config.js file.
const path = require('path');
module.exports = async ({ config }) => {
config.module.rules.push({
test: /\.(sass|scss)$/,
use: ['resolve-url-loader'],
include: path.resolve(__dirname, '../')
});
config.module.rules.push({
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
use: [
{
loader: 'file-loader',
query: {
name: '[name].[ext]'
}
}
],
include: path.resolve(__dirname, '../')
});
return config;
};
this is how I import the images
import arrow from '../../static/arrow.png';
I got the image source like
<img src="data:image/png;base64,ZXhwb3J0IGRlZmF1bHQgX193ZWJwYWNrX3B1YmxpY19wYXRoX18gKyAiQmFubmVyV2Vla2VuZDIucG5nIjs=" alt="test">

Module not found: Error: Can't resolve './component/Hello'

I´m trying to import a simple Component but the webpack seems to cant find it. The route is good and the "resolve" in the webpack config is great too, therefore I cant understand where is the issue.
Give it at look please.
By the way, its a Sails/React environment.
ERROR in ./assets/src/component/Hello.jsx 6:12
Module parse failed: Unexpected token (6:12)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
Hello.jsx:
import React from 'react'
class Hello extends React.Component {
render() {
return(
<div> // Err supposed to be here (line6)
Hello World!
</div>
)
}
}
export default Hello;
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import Hello from './component/Hello'
const App = () => {
return (
<div>
Simple Sails-React stater
<Hello/>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
.babelrc:
{
"presets": ["#babel/env", "#babel/react"]
}
webpack config file:
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
entry: './assets/src/index.js'
},
output: {
path: __dirname + '/.tmp/public',
filename: 'bundle.js'
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
{
use: ['style-loader', 'css-loader'],
test: /\.css$/
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
plugins: [
new HtmlWebpackPlugin({
template: 'assets/src/index.html'
})
]
};
the structure is like this:
-src
--component
----Hello.jsx
--index.js
--index.html
Could you try change extension to Hello.js or change bable-loader test to
test: /\.(js|jsx)$/,

React-Date "SingleDatePicker" not working as expected?

I am using react-dates and trying to implement singledatepicker. All the functionality is working but I dont know why all the default styles are gone. I am also using babel "transform-class-properties"
import React from 'react';
import moment from 'moment'
import 'react-dates/initialize';
import {SingleDatePicker} from 'react-dates';
import 'react-dates/lib/css/_datepicker.css';
const now= moment();
export default class ExpenseForm extends React.Component{
state={
description:'',
note:'',
amount:'',
createdAt:moment(),
calendarFocused:false
}
onDateChange = (createdAt)=>{
this.setState(()=>({createdAt}));
}
onFocusChange =({focused})=>{
this.setState(()=>({calendarFocused:focused}))
}
render(){
return(
<div>
<h3>ExpenseForm</h3>
<form>
<SingleDatePicker
date={this.state.createdAt}
onDateChange={this.onDateChange}
focused={this.state.calendarFocused}
onFocusChange={this.onFocusChange}
/>
</form>
</div>
)
}
}
Here is my Webpack config file and it is loaded with css-loader
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.resolve(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},{
test: /\.s?css$/,
use:['style-loader','css-loader','sass-loader']
}
]
},
devtool:'cheap-module-eval-source-map',
devServer:{
contentBase:path.resolve(__dirname, 'public'),
historyApiFallback:true
}
};
I had exact the same problem when integration react-dates into my project, and I believe the root cause is that the css module in your project also compile the css of react-dates which leads to missing of the style. To solve this problem, you could modify the rule in your module like:
...your original css module rule
exclude: [
/node_modules/
]
after applying this rule, you might encounter another issue which is that these css files can't be properly handled due to being excluded, you should then add another css module to handle those css file that you don't want to mess with, for example:
exports.vendorCss = {
test: /\.(css|scss|sass)$/,
include: [/node_modules/],
loaders: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'sass-loader',
},
],
};
and there you have it!! Hope this can help!

Webpack doesn't understand React's syntax

I am learning both React and Webpack. Now I have written a component that displays a name ;-)
const app = document.getElementById('app');
class World extends React.Component {
constructor(props) {
super(props);
this.name = 'Tomek';
this.callByName = this.callByName.bind(this); /* Or bind directly when calling */
}
callByName() {
alert(this.name);
}
render() {
return (
<div>
<h2>Hello, {this.name}</h2>
<button onClick={this.callByName}>Alert</button>
</div>
)
}
}
ReactDOM.render(<World />, app);
I import it with React and ReactDOM:
import React from 'react';
import ReactDOM from 'react-dom';
import './components/posts/index.js';
I use Webpack to process my JS:
module.exports = {
entry: [
'./_babel/index.js'
],
output: {
path: __dirname + '/_js',
filename: 'index.js'
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }
]
}
};
Unfortunately, when I run webpack, I get
ERROR in ./_babel/components/posts/index.js
Module build failed: SyntaxError: /Users/tomek/Sites/wordpress/wp-content/themes/Devoid/_babel/components/posts/index.js: Unexpected token (17:6)
render() {
return (
<div>
<h2>Hello, {this.name}</h2>
<button onClick={this.callByName}>Alert</button>
</div>
Propably I just forgot something, but I can't seem to find what.
You need to add the react loader to your webpack.config.js. I also suggest adding ES2015 loader. Try this:
module.exports = {
entry: [
'./_babel/index.js'
],
output: {
path: __dirname + '/_js',
filename: 'index.js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {presets: ['es2015']}
},
{
test: /\.jsx$/,
loader:'babel-loader',
query: {presets: ['es2015', 'react']}
}
]
}
};

Resources