Rendering a 'multiple' page App from one React file - reactjs

Hello fellow SO users !
I have a question about react and trying to display a multiple page application all in one html document but not loading everything at the beginning of course but whenever each one page is accessed.
So here's an example:
return(
<div>{
if something<*MainPage/>
else<*SecondPage/>}
</div> );
Is something like this possible ?
Thank you in advance !
Have a great day !

Yes it is possible, Consider the example code below
class User extends React.Component {
render() {
if (this.props.isGuest) {
return <h1>You are guest</h1>
}else {
return <h1>You are logged in</h1>
}
}
}
ReactDOM.render(<User isGuest={false} />,document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
As you can see the line: this.props.isGuest
I have passed it false, So you are able to see:
You are logged in

Related

Mutiple ReactDOM.render functions?

I'm starting to learn react and getting a problem when calling multiple ReactDOM.render functions:
react:
class Header extends React.Component{
render(){
return(
<div>
<p>Test1</p>
</div>
)
}
};
class Main extends React.Component {
render(){
return(
<section>
<p>Test2</p>
</section>
)
}
};
ReactDOM.render(<Main />, document.getElementById('root2'));
ReactDOM.render(<Header />, document.getElementById('root'));
html part:
<body>
<div id="root"></div>
<div id="root2"></div>
</body>
I'm getting the error:
Target container is not a DOM element.
When searching for this problem I got the information that it should be possible to call ReactDom.render multiple times. So I appreciate your help!
Edit: Just tried it with one html tag and changed the id. It seems to have a problem when the id is not "root"...
You are right, you should be able to call render multiple times in your code.
But instead of doing that why don't you do this:
Class App extends Component {
render(){
<React.Fragment>
<Header />
<Main />
</React.Fragment>
}
}
ReactDOM.render(<App />, document.getElementById('root'))
This is easier, correct and performance superior.
I really see no reason as to why soomeone woudld need to put 2 different renderers on one page. Its just putting more strain on the browser for no reason and it will slow down your application.

How to embed React Components in html pages

I want build a React component like
class MyComponent extends React.Component {
render(){
return (<div>This is a simple component</div>);
}
}
and use it like
<MyComponent></MyComponent>
in several different pages and even multiple times in a single html page.
I dont want to create a SPA just to enhance my web application's UI with React components.
Use
ReactDOM.render(<MyComponent />, document.getElementById('id'));
You can render in your HTML like this:
<div id="id"></div>
What you are asking for is not possible right now with React, you want to use what is known as web components.
https://webdesign.tutsplus.com/articles/how-to-create-your-own-html-elements-with-web-components--cms-21524
Read this to learn how to.
The other method is obviously
ReactDOM.render(<MyComponent />, document.getElementById('id'));
If you have to stick with React.
In index.jsx change the typical search for element root getElementById and change the logic to a getElementsByTagName scheme.
let elements=document.getElementsByTagName('MyComponent');
for (element of elements){
ReactDOM.render( <MyComponent />, element );
}
Simply adding React components into HTML code is not possible, because <MyComponent></MyComponent> is not HTML at all, it is JSX.
Explaination
JSX is a special syntax that can be 'transpiled' to Javascript, so in essence <MyComponent></MyComponent> will end up beeing Javascript code, which obviously can not just be put into HTML code.
The Javascript code generated from JSX then will be executed and generates actual HTML code.
It is possible to add HTML tags into JSX, because HTML can be interpreted as JSX (and will be transpiled to Javascript as well), like:
class MyComponent extends React.Component {
render(){
return <div>
<h2>HTML in JSX works</h2>
<SomeOtherJsxComponent />
</div>;
}
}
But it is not possible to add JSX into HTML, like:
<body>
<div>
<JsxInHtmlDoesNotWork />
</div>
</body>
React is Javascript, so everything that is necessary to add Javascript functionality to HTML also applies to adding React to HTML.
(nearest) Solution
So what you could do is to move your existing HTML into to some JSX wrapper (which is probably not what you would like to do, because this goes in the direction of creating a SPA, what you don't want), e.g.:
<html><head>
<title>My web site</title>
</head><body>
<h1>Some HTML title</h1>
<p>Some HTML content.</p>
<!-- add a container, where you want to include react components -->
<div id="injected-react-content"></div>
<!-- import the react libraray -->
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
<!-- setup react root component other components -->
<script type="text/babel">
class RootComponent extends React.Component {
render(){
return <div>
<MyComponent />
</div>;
}
}
class MyComponent extends React.Component {
render(){
return (<div>This is a simple component</div>);
}
}
const domContainer = document.querySelector('#injected-react-content');
ReactDOM.render( React.createElement(RootComponent), domContainer );
</script>
</body></html>
For some more background information on how to add React to an existing HTML website, see e.g.:
stackoverflow.com/questions/65917670/how-to-use-react-components-as-part-of-legacy-html-js-app
stackoverflow.com/questions/69607103/react-component-not-displayed-in-html
There are couple of options which can be explored here
parcel bundle
https://javascriptpros.com/creating-react-widgets-embedded-anywhere/
direflow bundle
https://jhinter.medium.com/using-react-based-web-components-in-wordpress-f0d4097aca38

react render doesn't show anything

My react codepen is not showing anything.
JS
class HelloWorld extends React.Component {
render() {
return (<div>Hello World!</div>);
}
}
var app = document.getElementById("mainapp");
React.render(<HelloWorld />, app);
HTML
<div id='mainapp'></div>
I imported React and ReactDOM trough a cdn. And if I type React/ReactDOM in the console it is imported correctly. This code doesn't show any errors yet I see nothing. I tested this on multiple browsers (chrome, firefox, icecat) but still no results... I'm using bable is a preprocessor.
ReactDOM.render not React.render.
class HelloWorld extends React.Component {
render() {
return <div>Hello World!</div>;
}
}
var app = document.getElementById("mainapp");
ReactDOM.render(
<HelloWorld/>,
app
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
<div id='mainapp'></div>
Your component needs to return an element instead of a naked string. Try to modify it to <div>Hello World!</div>
Two things
You need to return a valid react element
Use ReactDOM.render instead of React.render
Snippet
class HelloWorld extends React.Component {
render() {
return <div>"Hello World!"</div>
}
}
var app = document.getElementById("mainapp");
ReactDOM.render(<HelloWorld />, app);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="mainapp"></div>
Also see this answer on why you should use ReactDOM
react vs react DOM confusion

Implement HTML Entity Decode in react.js

I am outputting the text using API from the server, and I have an admin which has the html fields for facilitating filling the content. The issue in here that now the text displaying with html codes. How I can get rid of that undeeded html codes. I guess I have to use html entity decode? How I will implement that in react project? Below you see that the text illustrates not only text and html code.
export class FullInfoMedia extends React.Component {
render() {
const renderHTML = (escapedHTML: string) => React.createElement("div", { dangerouslySetInnerHTML: { __html: escapedHTML } });
return (
<div>
<div className="about-title">
<div className="container">
<div className="row">
<img className="center-block" src={this.props.about.image}/>
<h2>{this.props.about.title}</h2>
{renderHTML(<p>{this.props.about.body}</p>)}
</div>
</div>
</div>
</div>
);
}
}
You can use dangerouslySetInnerHTML, but be sure you render only your input, not users. It can be great way to XSS.
Example of using:
const renderHTML = (rawHTML: string) => React.createElement("div", { dangerouslySetInnerHTML: { __html: rawHTML } });
And then in a component:
{renderHTML("<p>&nbsp;</p>")}
Even though you can use dangerouslySetInnerHTML it's not really a good practice, and as stated by Marek Dorda it's a great thing for making your app XSS vulnerable.
A better solution would be to use the he library. https://github.com/mathiasbynens/he
This would be an example of how would your component look with it.
import he from 'he'
export class FullInfoMedia extends React.Component {
render() {
const renderHTML = (escapedHTML: string) => React.createElement("div", { dangerouslySetInnerHTML: { __html: escapedHTML } });
return (
<div>
<div className="about-title">
<div className="container">
<div className="row">
<img className="center-block" src={this.props.about.image}/>
<h2>{this.props.about.title}</h2>
{ he.decode(this.props.about.body) }
</div>
</div>
</div>
</div>
);
}
}
Also, if it were my codebase, I would most likely move the decoding to the API call, and in the component just consume the value that comes from the store
You can simply try this, it decodes text and then display.
<p dangerouslySetInnerHTML={{__html:"&nbsp;"}}/>

What does it mean when they say React is XSS protected?

I read this on the React tutorial. What does this mean?
React is safe. We are not generating HTML strings so XSS protection is the default.
How do XSS attacks work if React is safe? How is this safety achieved?
ReactJS is quite safe by design since
String variables in views are escaped automatically
With JSX you pass a function as the event handler, rather than a string that can contain malicious code
so a typical attack like this will not work
const username = "<img onerror='alert(\"Hacked!\")' src='invalid-image' />";
class UserProfilePage extends React.Component {
render() {
return (
<h1> Hello {username}!</h1>
);
}
}
ReactDOM.render(<UserProfilePage />, document.querySelector("#app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
but ...
❗❗❗Warning❗❗❗
There are still some XSS attack vectors that you need to handle yourself in React!
1. XSS via dangerouslySetInnerHTML
When you use dangerouslySetInnerHTML you need to make sure the content doesn't contain any javascript. React can't do here anything for you.
const aboutUserText = "<img onerror='alert(\"Hacked!\");' src='invalid-image' />";
class AboutUserComponent extends React.Component {
render() {
return (
<div dangerouslySetInnerHTML={{"__html": aboutUserText}} />
);
}
}
ReactDOM.render(<AboutUserComponent />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
2. XSS via a.href attribute
Example 1: Using javascript:code
Click on "Run code snippet" -> "My Website" to see the result
const userWebsite = "javascript:alert('Hacked!');";
class UserProfilePage extends React.Component {
render() {
return (
<a href={userWebsite}>My Website</a>
)
}
}
ReactDOM.render(<UserProfilePage />, document.querySelector("#app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Example 2: Using base64 encoded data:
Click on "Run code snippet" -> "My Website" to see the result
const userWebsite = "data:text/html;base64,PHNjcmlwdD5hbGVydCgiSGFja2VkISIpOzwvc2NyaXB0Pg==";
class UserProfilePage extends React.Component {
render() {
const url = userWebsite.replace(/^(javascript\:)/, "");
return (
<a href={url}>My Website</a>
)
}
}
ReactDOM.render(<UserProfilePage />, document.querySelector("#app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
3. XSS via attacker controlled props
const customPropsControledByAttacker = {
dangerouslySetInnerHTML: {
"__html": "<img onerror='alert(\"Hacked!\");' src='invalid-image' />"
}
};
class Divider extends React.Component {
render() {
return (
<div {...customPropsControledByAttacker} />
);
}
}
ReactDOM.render(<Divider />, document.querySelector("#app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Here are more resources
Exploiting Script Injection Flaws in ReactJS Apps
The Most Common XSS Vulnerability in React.js Applications
How Much XSS Vulnerability Protection is React Responsible For?
https://github.com/facebook/react/issues/3473#issuecomment-90594748
https://github.com/facebook/react/issues/3473#issuecomment-91349525
Avoiding XSS in React is Still Hard
Avoiding XSS via Markdown in React
React automatically escapes variables for you... It prevents XSS injection via string HTML with malicious Javascript.. Naturally, inputs are sanitized along with this.
For instance let's say you have this string
var htmlString = '<img src="javascript:alert('XSS!')" />';
if you try to render this string in react
render() {
return (
<div>{htmlString}</div>
);
}
you will literally see on the page the whole string including the <span> element tag. aka in the browser you will see <img src="javascript:alert('XSS!')" />
if you view the source html you would see
<span>"<img src="javascript:alert('XSS!')" />"</span>
Here is some more detail on what an XSS attack is
React basically makes it so you can't insert markup unless you create the elements yourself in the render function... that being said they do have a function that allows such rendering its called dangerouslySetInnerHTML... here is some more detail about it
Edit:
Few things to note, there are ways to get around what React escapes. One more common way is when users define props to your component. Dont extend any data from user input as props!

Resources