ReactJS: Why isn't my div showing up? - javascript

I have basic index.html and index.js that don't do much except the minimum. My html file is this:
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="container"></div>
</body>
<script src="fb's react url"></script>
<script src="fb's reactDOM url"></script>
<script type="text/jsx" src="index.js"></script>
and my index.js file is this:
var Grid = React.createClass({
getInitialState: function() {
return {
grid: "Ola!"
}
},
componentDidMount: function() {
},
render: function() {
return ( < div > {
Ola!
} < /div >
);
}
}
);
ReactDOM.render( < Grid / > ,
document.getElementById('container')
);
When I load my page (index.html) in Google Chrome, I just get a blank white screen. The console isn't outputting any errors. What could be going wrong? I am very new to React.js and most web technologies.

https://jsfiddle.net/9fcyrbj3/
In JSX, everything that is inside curly braces will be evaluated as a Javascript, so it needs to be a valid JS expression. { Ola! } therefore would need to become { 'Ola!' }.
However, you don't need curly braces here and you could simplify it like this:
render: function() {
return (< div > Ola! < /div >);
}

Change your render method as below. The {} in ReactJS evaluates the content inside as expression
render: function() {
return (
<div> Ola! </div>
);
}

Related

JS: Display certain div if browser is IE

I have this react project that doesn't work in Internet Explorer, and we don't intend it to work in IE.
So when rendering the index.html there is the usual root div that renders react.
I want not to render that root div when browser is IE but a different div, with a message warning that the app doesn't work in IE
I can know if the browser is IE like so:
const isIE = !!window.MSInputMethodContext && !!document.documentMode
So I'm trying to change the html div output depending of isIE and I'm not quite sure how.
Logic:
if isIE - true render <div id="root"></div>
if !isIE - false render <div>Browser not supported</div>
Tried something like this:
<html>
<head>
<meta charset="utf-8" />
<% _.map(css, (item) => { %><link href="<%= item %>" rel="stylesheet"><% }) %>
</head>
<body>
<script>
const isIE = !!window.MSInputMethodContext && !!document.documentMode;
if (isIE) { document.getElementById('root').innerHTML += '<p>IE!!</p>' } // or something similar
</script>
<div id="root"></div>
<script>window.__ENVIRONMENT__ = Object.freeze(<%= JSON.stringify(environment) %>)
</script>
<% _.map(js, (item) => { %><script src="<%= item %>"></script><% }) %>
</body>
</html>
Also tried a logic returning the html as a string like so:
<script>
if (isIE) { return '<div>Browser not supported</div>'; }
else { return '<div id="root"></div> }
</script>
And this
const IEdiv = '<div>This is IE</div>';
const rootDiv = '<div id="root"></div>';
if (isIE) { IEdiv.append('body'); }
else { rootDiv.append('body'); }
None of this works
React shouldn't work out of the box with any version of IE as far as I can tell. It requires (or at least used to require) react-app-polyfill to get anywhere.
You're also going to have problems with const as it's only supported by IE11. If the only version of IE you're concerned with is IE11 you should be fine for this.
UPDATED ANSWER
I created a sample myself to see what I could do. I first experimented with loading the <div> into the page with JS, and hit a nasty IE error in being unable to add elements to the document.
So I changed my approach back to yours - editing the existing <div>. The problem isn't your code, the problem is that your script is being ran before the <div> is present in the DOM (to be accessed). Put the <div> above the script (or move the JS to an external file and load it in) and it should work as you intend it to.
Here's my sample for reference:
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<div id="root"></div>
<script>
var isIE = !!window.MSInputMethodContext && !!document.documentMode;
console.warn(isIE);
if (isIE) {
var root = document.getElementById('root');
root.innerHTML += 'IE!!';
}
else {
var root = document.getElementById('root');
root.innerHTML += 'hello hello hello';
// you may also need to defer React being loaded in
}
</script>
</body>
</html>

How to run regular JavaScript in React/Preact application

I am trying to use masonry in a Preact app, tried several React plugins using react/compat but they are all failing.
This is how I'm trying:
const App = () => (
<Landing name="shoecare">
<!-- all the working code -->
<!-- here -->
<script src="https://unpkg.com/masonry-layout#4.2.2/dist/masonry.pkgd.min.js"></script>
<script>
var grid = document.querySelector(".how__list");
new Masonry(grid, {
itemSelector: ".how__item",
columnWidth: document.querySelctor('body').clientWidth / 2 - 16,
});
</script>
<!-- end -->
</Landing>
);
clab(<App />);
But it fails to compile:
Is it posible?
I managed to run some regular JS onclick, like so;
<span class="services__nav-previous" onClick={(e) => scrollLeft()}>
i guess you're using functional components, so to have any js code inside of them you should do it like this
const App = () => {
// your js code here
return (
// here you put your components
)
}
EDIT: and you don't put < script >< /script > inside of your functional component, you add them in your index.html file, not in app.js

Non blocking render in ReactJS

I'm learning ReactJS and trying to build some application on it.
When I'm trying to modify my state and render, my page is freezing and can't do anything until the render is finished when my components become huge.
I found that I can use shouldComponentUpdate to optimize my code, but the question comes to me is: Can I make this render procedure be non blocking? And so I can tell the user that the page is processing some heavy loading executions and please wait or maybe show the progress of the execution? Or if the user can cancel the render, for example, for a live editor, if user edit the content of the editor, the "preview" section will stop rendering old content and trying to render new content without blocking the editor UI?
Here's the heavy loading example code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>React Tutorial</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div id="content"></div>
<script type="text/babel">
var Box = React.createClass({
render: function() {
return (
<div>Box</div>
);
}
});
var CommentBox = React.createClass({
getInitialState: function() {
return {box_count: 5};
},
heavyLoadRender: function() {
this.setState({box_count: 40000});
},
render: function() {
var render_box = [];
for (var i=0; i<this.state.box_count; i++) {
render_box.push(<Box />);
}
return (
<div>
{render_box}
<button onClick={this.heavyLoadRender}>Start</button>
</div>
);
}
});
ReactDOM.render(
<CommentBox />,
document.getElementById('content')
);
</script>
</body>
</html>
When I press Start, the page will freeze and no response until all Box is rendered. Is it possible to add a button named Cancel which user can cancel the render and clear all boxes?
This is a great question, and a perfect use case for setTimeout which can schedule an update to the next round of the event loop.
Rather than store the number of components to render, store an array of components, and render them directly. jsfiddle
var CommentBox = React.createClass({
getInitialState: function() {
return { boxes: [<Box key="first" />] };
},
heavyLoadRender: function() {
setTimeout(() => {
if (this.state.boxes.length < 50000) {
this.setState({
boxes: this.state.boxes.concat(<Box key={this.state.boxes.length} />)
})
this.heavyLoadRender()
}
})
},
render: function() {
return (
<div>
<button onClick={this.heavyLoadRender}>Start</button>
{this.state.boxes}
</div>
)
}
})
Update:
If you only want to show the state once the array is filled up, don't display anything until it hits that size:
This did not work:
{ this.state.boxes.length === 50000 && this.state.boxes }
Hope is not lost though! Use style!
<div style={{ display: this.state.boxes.length === 50000 ? 'block' : 'none' }}>
{ this.state.boxes }
</div>
If you want to increase the speed, you can push more than item per setTimeout
var newBoxes = []
for (var i = 0; i < 5; i++) {
newBoxes.push(<Box />)
}
this.setState({
boxes: this.state.boxes.concat(newBoxes)
})
updated fiddle. I think this whole class of problems is going to take time to perform. In batches of 10,000 the basic box component doesn't block and you could easily throw a loading spinner up there.

React error "Uncaught TypeError: type.toUpperCase is not a function" on a hello world app

I have started dabbling with reactjs, and on following a tutorial and I got the error on the title, just on running a very simple hello world app. Below is the single page code I have:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://fb.me/react-0.13.3.js"></script>
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
</head>
<body>
<script type="text/jsx">
// Define a class
var HelloWorld = React.createClass({
render: function() {
return <div>
Hello World!
</div>
}
});
// create element with this class
var element = React.createElement({HelloWorld});
// Render this class and place it in the body tag
React.render(element, document.body);
</script>
</body>
</html>
Any hints or resolution are very much appreciated.
In my case I have created a React element, but I forgot to export it on the end of the file:
var React = require('react');
var About = React.createClass({
render: function(){
return (
<div>
<h1>The about page</h1>
</div>
);
}
});
export {
About, About as default
};
There is a mistake in the following line:
var element = React.createElement({HelloWorld});
It should be:
var element = React.createElement(HelloWorld);
Notice the lack of the curly braces.
Hey the proper way to render the element is
React.render(<HelloWorld />, document.body);
You don't need to create the element first. So overall your code should look like
var HelloWorld = React.createClass({
render: function () {
return <div > Hello World! < /div>
}
});
React.render( < HelloWorld / > , document.body);

How to render accents in ReactJs?

I'm trying render an element which has an accent character using ReactJS and JSX, but it's not returning what I wanted.
My JSX:
var Orcamento = React.createClass({
render: function() {
return (
<div>
<h1>Orçamento</h1>
</div>
);
}
});
React.render(
<Orcamento/>,
document.getElementById("orcamento")
);
My rendered javascript:
var Orcamento = React.createClass({displayName: "Orcamento",
render: function() {
return (
React.createElement("div", null,
React.createElement("h1", null, "Orçamento")
)
);
}
});
React.render(
React.createElement(Orcamento, null),
document.getElementById("orcamento")
);
And my result in browser:
Orçamento
I've set <meta charset="UTF-8"> in my index file inside the head tag, accent characters works in page title and body if this word is typed direct in page content, but is not working when it's rendered by ReactJs
How can I fix this problem?
I resolved! the problem is because I'm compiling JSX using gulp, and file generated is not UTF-8, so I save as file in UTF-8 that is working!
What you see, Orçamento, it's a result of a UTF-8 byte array being rendered in ASCII, probably codepage ISO 8859-1.
ReactJS doesn't support non-ASCII characters within HTML.
Try this:
var Orcamento = React.createClass({
render: function() {
return (
<div>
<h1> { 'Orçamento' } </h1>
</div>;
);
}
});
Or simply replace orçamento by Orçamento.
This is well explained in the JSX gotchas.
Also using the charset utf-8, try using this library:
https://github.com/mathiasbynens/he
import { decode } from 'he';
class Post extends Component {
render() {
<h1>{ decode(this.props.post.title) }</h1>
}
}

Categories

Resources