using npm package in react app - javascript

I have some ad-hoc javascript knowledge and am trying to learn react, but can't seem to locate documentation on how to use imports correctly. Specifically, I have a quick app that fetches a value from an api I set up, and I would like to format the number using katex. There is a react-katex package I installed using npm, but the instructions don't seem to cover how to accomplish this using webpack/jsx/whatever.
More specifically, how would I use the package? The documentation says to use it thus
var BlockMath = ReactKaTeX.BlockMath;
ReactDOM.render(<BlockMath math="\\int_0^\\infty x^2 dx"/>, document.getElementById('katex-element'));
but when I do this in the example code below I get an error that the element katex-element is undefined. I realize (I think) that the first line is replaced by the import command, so I know I don't need that, but where do I put the BlockMath call to get it to render the number in tex?
Here is my example app, I've tried a few things, but I either end up getting undefined errors, or no result at all:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
// ?? import 'react-katex';
class App extends Component {
constructor(props) {
super(props)
this.state = {
number: 0
}
}
componentDidMount() {
fetch('http://localhost:4001/api/get_number')
.then(data => data.json())
.then(data => {
this.setState({
number: data.number
})
})
}
render() {
const number = this.state.number
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
Also <span id="katexElement">{number}</span>
</p>
</div>
);
}
}
export default App;
I think there is a similar question here: Is there a different between using an npm package in Node.js vs using it in React / webpack?

you can import it using
import {InlineMath, BlockMath} from 'react-katex'
Notice the curly braces {}, it will get only specified property from the library and not the whole library.
and can use these component directly in your jsx, like:
const inlineMath = (
<div>
<InlineMath math="\\int_0^\\infty x^2 dx"/>
</div>
);
Notice: Please dont forget to add css.
Don't forget to import KaTeX CSS file (see example/index.html).
Use this inside your index.html to import css in your code.
<link rel="stylesheet" href="../node_modules/katex/dist/katex.min.css">
I would suggest you to use {} braces to get only the specific property from the library rather than loading the whole library at once. Also it makes the code much more clearer and readable.

Using import {InlineMath, BlockMath} from 'react-katex' would let you leverage InlineMath.function().
Alternatively, you should just be able to include
import ReactKatex from react-katex
which would then allow you to access the entire library via ReactKatex.subexport.function where subexport is a nested module (such as InlineMath from the example above) and function is a defined function within that submodule.

Related

How do I link my javascript files in react when converting from HTML,CSS,JS into JSX, CSS, JS?

I have a typical website created with HTML, CSS, Javascript and I'm trying to convert it into react.
I can convert my HTML into JSX pretty easily with an online converter and my CSS is the same, I just have to import it differently.
But now I'm confused about how to link up my javascript files. Because my HTML is now JSX which is in a Javascript file as well.
Normally in html this is all I need to do to link my java script and everything works:
<script type="text/javascript" src="js/main.js"></script>
How would I do this in react such that my JSX will have the same functionality as did my HTML?
Right now whether I try to import it from file location:
import './javascript/main.js'
It doesn't do anything. I'm not getting any errors. My JSX and CSS works fine and all I have for my CSS is (this import works fine):
import './css/main.css'
If it should work, please let me know, it must mean there's an error elsewhere that I have to sort out.
Thanks in advance
I don't think you can import js code on a react app, probably you have to create react-app first, then create its components and add you javascript code within these components, it´s pretty easy, i recomment you to read the documentation of react and see how it works. Hope it helped you.
You can include JavaScript functions inside JSX itself :
import React from 'react';
const Something=()=>{
// Your javascript functions :
return(
<div>
Your Html here
</div>
)
}
export default Something
// Or if You are using Class Component :
import React, { Component } from 'react';
class Something extends Component {
state = { }
// Your Javascript Functions
render() {
return (
<div>
Your HTML goes here
</div>
);
}
}
export default Something;
and if you want to import js file from another location you have to include export in your function:
export const Name=()=> {
}
and import:
import {Name} from '/location';

Convert string React Component to jsx again

I have one question, because read javascript file from NodeJS and send to the client and here I reveive all file as string (which is obvious) and here is my question. Is any solution to convert string component again to the jsx? This is no only html tags so dangerouslySetInnerHTML or similar methods don't work.
My string components looks like typical React component, something like that:
import React from 'react';
import { Row } from 'react-bootstrap;
import Home from './Home'
......
const Index = () => {
const renderHelloWorld = <h1>Hello World</h1>
return (
<div>{renderHelloWorld}</div>
)
}
export default Index;
So this is string I'm struggling with how convert it to jsx (maybe this is impossible) and I should use Server Side Rendering with React methodfs like ReactDOMServer?
You can use just plain old JavaScript to do the trick.
document.querySelector('#elementToBeReplace').innerHTML = renderHelloWorld;
Another Option with react.js is use of dangerouslySetInnerHTML.
<div dangerouslySetInnerHTML={{ __html: renderHelloWorld }} />
Or You can use html-react-parser.
import Parser from 'html-react-parser';
const renderHelloWorld = <h1>Hello World</h1>
<div>{Parser(renderHelloWorld)}</div>
Try this library https://www.npmjs.com/package/react-html-parser.
A utility for converting HTML strings into React components. Avoids the use of dangerouslySetInnerHTML and converts standard HTML elements, attributes and inline styles into their React equivalents.
So, solution for my problem is very popular and simple (in early project stage), to understand problem and fix it we need to go back to the server part of the app. For React applications if we want render jsx file from the server, we have to use server side rendering and above problem will be gone. Maybe I show step by step how enable rendering React component in te server.
Configure backend to enable the ES6 features
Install babel packages
npm install #babel/core #babel/node #babel/preset-env #babel/preset-react --save-dev
There is many ways to configure Babel, I use the nearest package.json for this.
{
......,
/*This have to be in the top level in package.json*/
"babel":{
"presets":[
"#babel/preset-env",
"#babel/preset-react"
]
}
}
More information about babel packages and configurations: https://babeljs.io/docs/en/
Send React component to the client
For this we have to install react and react-dom packages in server side
npm install react react-dom
For example in your server,js or route.js file:
.... //necesarry imported modules
import ReactDOMServer from 'react-dom/server'
import Index from './Index';
router.get('/exampleRoute', (req, res) => {
.... //your route business logic
res.send(ReactDOMServer.renderToString(<Index/>))
})
Render view in the client
...//correct React component
const[state, setState] = useState({Component: ''});
fetch('/exampleRoute')
.then(response => response.json())
.then(data => setState(state => ({...state, Component: data.data));
....
return(
<div dangerouslySetInnerHTML={{ __html: state.Component }}></div>
)
This is only simple example how you can render React component from backend if this is necasarry. This is not guide for complex server side rendering in application which is more complicated thing, but no difficult thing.

How to load a React.Component from a CDN and render into another React.Component

Note: None of the answers actually work [DO NOT DELETE THIS NOTE]
simple question, I got a project,
npx create-react-app react-project (consider this Project Y)
now, inside this project's App.js
import React, { Component } from 'react'
export default class App extends Component {
render() {
return (
<div>
HELLO
</div>
)
}
}
now in CDN I have another Comp.js (Consider this Project X)
https://codepen.io/sirakc/pen/ZEWEMjQ.js
import React, { Component } from 'react'
export default class Comp extends Component {
render() {
return (
<div>
WORLD
</div>
)
}
}
now I want to show the Comp.js into App.js as if you are taking it from local source folder
so
import React, { Component } from 'react'
//somehow somewhere import Comp.js and then <Comp/>
export default class Comp extends Component {
render() {
return (
<div>
HELLO <Comp/>
</div>
)
}
}
and ofc the output should be
HELLO WORLD
when I run the project react-project and if in the CDN I change WORLD to EARTH it should change WORLD to EARTH in the output as well
so now react-project's output is HELLO EARTH
I am putting all my rep into a bounty for this, upvote if you like this question to help me attract attention.
NOTE: my need is to show React project X inside React project Y without touching much of project Y and ofc update the project X without updating anything inside project Y, so yea the <script src='chunk.js'/> isn't gonna work here, the chunk name changes, if you can find a way to not make it change, then its great, do share. If you know a working way to do this bundled into chunk.js DO SHARE!
ANY WAY OF DOING THIS IS WELCOMED, as long as Project X is independent of Project Y and I can make changes to Project X without changing Project Y
There are a few options you have at hand.
Option 1 - Create a NPM Package
Turn Project X into a module.
This will mean you will go to Project X development folder, and run npm login and npm publish. You can read more about that here
After that, once your package is on NPM You can go to Project Y and do the following:
import React, { Component } from 'react'
import Comp from 'my-package'
export default class Comp extends Component {
render() {
return (
<div>
HELLO <Comp/>
</div>
)
}
}
Option 2 - Load a bundled JS
Instead of having your script load the following:
import React, { Component } from 'react'
export default class Comp extends Component {
render() {
return (
<div>
WORLD
</div>
)
}
}
This is JSX Syntax. And it cannot be read in plain Vanilla JS - thus you cannot just import it like <script src="myscript.js" /> since this is not valid JS without a parser like Babel.
I would go to Project X and run npm run build. After that I would get the bundle.js - bundled and minified script written in Plain JS. It would look something like this:
(this.webpackJsonpchrome_extension=this.webpackJsonpchrome_extension||[]).push([[2],[function(e,t,n){"use strict";e.exports=n(99)},,function(e,t,n){"use strict";function r(){return(r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";function r(e,t){if(null==e)return{};var n,r,i={},o=Object.keys(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)
Basically non-human readable code, which is parsable by <script src="myscript.js" /> tag. And then you would have to go to your index.html and inject it there, or use some of modules like react-script-tag
I would highly highly recommend going with Option #1. Since this is the preferred way to go. Look into creating NPM packages from your React project, and follow step by step.
Some more useful links about Option #1:
Create a simple React npm package in simple steps using CRA
How to publish your React component on npm
Hope this will guide you in the right direction, but the current way you are doing it is a no-go
EDIT - Tehnically there is an option #3, but I wouldn't recommend it.
Option 3 - Make your url provide just JSX, and load it in dangerouslySetInnerHtml.
Let's say your https://codepen.io/sirakc/pen/ZEWEMjQ.js would provide with this only:
<div>
WORLD
</div>
Technically, you could then turn your link into something more readable, like .txt extension, fetch it, store it in a variable, and load it in dangerouslySetInnerHTML.
for example:
const otherProjectJSX = somehowLoad(https://codepen.io/sirakc/pen/ZEWEMjQ.js)
const MyApp = () => <div dangrouslySetInnerHtml={otherProjectJSX} />
Basically it would be this:
const otherProjectJSX = '<div>WORLD</div>'
const MyApp = () => <div dangrouslySetInnerHtml={otherProjectJSX} />
I would not recommend this, but if it is only what is inside render() you care about - it might work after all.

FormattedHTMLMessage not working after package-update (looking for alternative/fix)

We have recently updated our website's npm packages (react-intl version 4.5.1) and we are using react-intl. The problem is, that we used the FormattedHTMLMessage component which doesn't seem to be working anymore. If I visit the page now there are elements with classnames displayed in the text.
We display the text via props:
import React from "react";
import {
FormattedMessage as FM,
FormattedHTMLMessage as FHM
} from "react-intl";
export default props => {
return(
...
<p className="fs-18 white-space-pre-line">
<FM id={props.descriptionKey} />
</p>
...
);
};
and in the .json file for the text it looks like this:
textDescription: "Sometext <span class='font-tilde-bold h3'>Sometext</span> Sometext"
Is there any good alternative or should we generally use another approach?
FormattedHTMLMessage was removed in version 4.
You can see in upgrade guild v3 -> v4.

Convert website from HTML,CSS,bootstrap & JQuery to React?

Hi guys hope you're fine, I'm student and I have this year to do some thing like a project to end my studies , so I chose to create a website (using React/Django) I already have the site but made by HTML,CSS,bootstrap & JQuery , so now i have to convert it to react , but i have a problem i don't know how to include some js files inside a components , every things else is going good, I need just what is in the js files to applied it in some components.
Hope you help me out.
cordially
You can have javascript code inside your components likewise
const Component = props => {
//javascript code
return (<div>-- Component JSX---</div>)
}
if the javascript code if just needed for the initializing of the component you can use react hooks to run a piece of code only one time after the component is created.
import React, { useEffect } from 'react';
const Component = props => {
useEffect(() => {
// javascript code
}, [])
return (<div>--Component JSX---</div>
}
the empty array as second argument indicates the useEffect hook that the effect should only be ran once after the component has been initialized.
So the way React works is you will be building "HTML" using React functional/class components like this example
import React from 'react';
//Just like a normal javascript function, it listens to in this
instance, the return statement. You're returning regular HTML.
function Navbar() {
return (
<div>This is some text built by react</div>
<p>Saying hello to react by building a functional component</p>
)
}
export default Navbar; //This right here is exporting the file so it can be
//used elsewhere just import it in other file.
So the return is where you will build your website, then in the next component you will import should look something like this.
Normally, it is called App.js or in some instances where it's more complex it's anythinng you want.
import Navbar from '../components/Navbar.js';
function App() {
return (
<Navbar /> //Now you don't have to write your main content in here you can
//just import it. Just like Navbar
<div>This is my main content in page</div>
)
}

Categories

Resources