How to Add html in React - reactjs

I'm starting to learn reactjs at the moment. I'm wondering how to add normal HTML-Tags in a react-app. Is i just possible to add them by using the render function or can I also just write normal HTML-Tags in my index.html file?
Cause when I'm doing so they're not displayed.
Just like:
const myelement = (<h1>some element</h1>);
ReactDOM.render(myelement, 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>
<div id="root"></div>
<div>just normal html</div>
</div>
Well, it works just fine here.. so there must be something wrong with my build..

If you're starting out, I recommend you bootstrap your apps using npx create-react-app. It'll give you a good sense of what a React app could look like, and some pointers for file structure.
Most React apps have an index.html file, which you can use like any normal HTML file. But, for the majority of your app, it's recommended to write your content in JSX (otherwise, you aren't getting the benefits of using React in the first place).
JSX
JSX looks very similar to regular HTML, with a handful of key differences:
Tag attributes tend to be in lowerCamelCase (onChange rather than onchange)
Instead of class (which is a reserved keyword in JavaScript), you need to use className
An Example Component
I've borrowed this sample code from React's official tutorial, which you should definitely check out if you haven't already.
This is a class Component, and your JSX goes inside of the render method:
import React from 'react';
class ShoppingList extends React.Component {
render() {
return (
<div className="shopping-list">
<h1>Shopping List for {this.props.name}</h1>
<ul>
<li>Instagram</li>
<li>WhatsApp</li>
<li>Oculus</li>
</ul>
</div>
);
}
}
What goes in index.html?
The only essential part of index.html is a <div id="root"></div>, which React will use to append the rest of the JSX.
This is also the place to add the usual metadata and icons.
As an example, here's the index.html file that comes with create-react-app. For most of my projects, I leave this pretty-much as-is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

In any given React component, there can only be one parent/top layer html element. You can get around this by using <React.Fragment> ...the rest of your html ... </React.Fragment> (or <>...</> depending on your version) or simply add a wrapping <div> around everything. JSX doesn't distinguish between "normal" html and "React" html, it just turns the React stuff into normal html (over simplification, but close enough for this question). Try it again and let me know if you encounter any problems.
const reactElement = (
<div>
React stuff
</div>
);
ReactDOM.render(
reactElement,
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>
<div id="root">
</div>
<div>
just normal html
</div>
</div>

Related

From where i can find this <div> tag i want to height equal to 0

There is a line of <div style={height: 50px}> where height is 50px i want to make it 0 in code but where it is located?
index.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/logo2flat.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/material-design-iconic-font/2.2.0/css/material-design-iconic-font.min.css">
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo1922.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bubblegum+Sans&display=swap" rel="stylesheet">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
There is a white spacing showing and height was the reason so I want to make it 0. I try to find in different files but i don't know where exactly it is
Any help will be appreciated
Thanks In Advance
I am assuming that you want to find react component responsible for that. You may want to use components tab in developer tools to find out which component is responsible for rendering a particular element. link - https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en With that you can hover on an element and corresponding component gets highlighted.
This looks something like following -
more information about how to use that - https://reactjs.org/blog/2014/01/02/react-chrome-developer-tools.html

How to have react app in the HTML without npm start or similar commands

I'm kinda new to ReactJS and don't even know if it's possible but I want my react app to be working in the browser from the .html file. without the need for calling the server and have it, working, only that way. ( I don't mind having a server to serve it obviously) just need to be able to have by calling the .html file
the public/index.html file:
<head>
<meta charset="utf-8">
<script src="/my_library/my_library.min.js"></script> <!-- needed for the project in the same folder the index.html is -->
<title>Demo</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start`.
To create a production bundle, use `npm run build`.
-->
</body>
</html>
the index.js (in src folder):
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
React.createElement(App),
document.getElementById('root')
);
The App.jsx in the src folder
import * as React from 'react';
import './App.css';
import { MyContainer } from './components/MyContainer/index';
class App extends React.Component {
render() {
return (
<div className={ 'App' }>
<header className={ 'App-header' }>
<h1 className={ 'App-title' }>
</h1>
</header>
<MyContainer />
</div>
);
}
}
export default App;
PS: I have been able to add React to my file... But this particular component that I want to add only works with NPM Start. and as you can see in the index.html file shown above is says
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
which is exactly what I aim to change. if any one can provide some guidance or help about this, would be much appreciated.
If you just want to use React within an HTML file within a browser maybe you could just include the React library with a script tag as well as your custom React scripts with script tags as well. Their documentation has a nice example of just using React within an HTML file. I created a Codebox with their sample example for this below where the like button is using react. However, if you want to use JSX syntax you will have to use Babel, to transpile JSX into native JavaScript, and link the library like such:
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
create_react_app gives you a lot of bells and whistles so you don't have to worry about setting up build configurations using tools such as webpack, babel, eslint, etc.. but this meant to give you a head start on building out an application so you can focus on the application itself and not configuration settings. Behind the scenes it's using webpack-dev-server to serve up your application, but for your use case I think it would be best to just add React as a script tag to an existing HTML page
'use strict';
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked this.';
}
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);
}
}
const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Add React in One Minute</title>
</head>
<body>
<h2>Add React in One Minute</h2>
<p>This page demonstrates using React with no build tooling.</p>
<p>React is loaded as a script tag.</p>
<!-- We will put our React component inside this div. -->
<div id="like_button_container"></div>
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<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>
<!-- Load our React component. -->
<script src="like_button.js"></script>
</body>
</html>
Hopefully that helps!

How can I add altmetrics badge to in ReactJS

I am trying to use altmetrics in one of the my article (PDF) in my website.
I tried to add the altmetric badges (here) to in reacts js but I could not manage.
Here is my trial:
First I tried to create a component and add to the page
class DownloadPDF extends Component {
render() {
return (
<div>
<script type="text/javascript" src="https://d1bxh8uas1mnw7.cloudfront.net/assets/embed.js"></script>
<div data-badge-details="right" data-badge-type="medium-donut" data-doi={"my-doi-number-here"} class="altmetric-embed"> </div>
Download PDF
</div>
);
}
}
The second is I tried to put in the page directly:
<div>
<script type="text/javascript" src="https://d1bxh8uas1mnw7.cloudfront.net/assets/embed.js"></script>
<div data-badge-details="right" data-badge-type="medium-donut" data-doi="my-doi-number-here" class="altmetric-embed"> my-crosreff-doi.pdf</div>
{<DownloadPDF />}
</div>
Can someone know how can I put altmetrics badges correctly in reactJS?
Thank you all answers.
For seeing the Altmetrics result in your page first you should add:
altmetrics external javascript file
<script type='text/javascript'src='https://d1bxh8uas1mnw7.cloudfront.net/assets/embed.js'></script>
2.
You should add your DOI wherever you want to display
<div class='altmetric-embed' data-badge-type='donut' data-doi="10.1038/nature.2012.9872"></div>
so this is for adding to html page but when you add in ReactJS web app we have a tiny problem.
Problem is adding external javascript file to in ReactJS page that you want to display the Altmetrics badge
So solution is we need to install an addition library that allows us to implement any external javascript file.
Check the link:
https://github.com/shaneosullivan/ReactDependentScript/
We need to add below code in your ReactJS page
...
render() {
return (
<div>
<ReactDependentScript
loadingComponent={<div></div>}
scripts={['https://d1bxh8uas1mnw7.cloudfront.net/assets/embed.js']}
>
<div></div>
</ReactDependentScript>
...
</div>
);
}
}
then you can add your the Altmetrics badge wherever you want in the page like this
<div data-badge-details="right" data-badge-type="medium-donut" data-doi="doi-numberhere" class="altmetric-embed"></div>
I think all you need to do as described https://api.altmetric.com/embeds.html
that you put the js script in any where in html , but react is virtual dom , so all you need is put in puplic in index.html in <body> under <div id"root"></div>
or like you named. just simple as that
There are two things you are missing
Adding the script to index.html file underpublicdirectory (if you have created your app usingcreate-react-app`)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<!-- Here we go with the external script -->
<script type='text/javascript' src='https://d1bxh8uas1mnw7.cloudfront.net/assets/embed.js'></script>
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
</body>
</html>
Change the class attribute to className in dom
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
// changed class to className
<div className='altmetric-embed' data-badge-type='donut' data-doi="10.1038/nature.2012.9872"></div>
</div>
);
}
}
export default App;

How to import bootstrap and fontasome in index.html reactjs app

Install bootstrap using this command (npm install bootstrap#4.0.0-alpha.6)
and my index.html file is:
According issue I can add the css from other front framework (https://maxcdn.bootstrapcdn.com/), and make it work. I d
<!doctype html>
<html lang="en">
<head>
<!-- The first thing in any HTML file should be the charset -->
<meta charset="utf-8">
<!-- Make the page mobile compatible -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Allow installing the app to the homescreen -->
<link rel="manifest" href="manifest.json">
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<meta name="mobile-web-app-capable" content="yes">
<title>Super Tax</title>
<script type="text/javascript">
(function(e,t){var n=e.amplitude||{_q:[],_iq:{}};var r=t.createElement("script")
;r.type="text/javascript";r.async=true
;r.src="https://cdn.amplitude.com/libs/amplitude-4.0.0-min.gz.js"
;r.onload=function(){if(e.amplitude.runQueuedFunctions){
e.amplitude.runQueuedFunctions()}else{
console.log("[Amplitude] Error: could not load SDK")}}
;var i=t.getElementsByTagName("script")[0];i.parentNode.insertBefore(r,i)
;function s(e,t){e.prototype[t]=function(){
this._q.push([t].concat(Array.prototype.slice.call(arguments,0)));return this}}
var o=function(){this._q=[];return this}
;var a=["add","append","clearAll","prepend","set","setOnce","unset"]
;for(var u=0;u<a.length;u++){s(o,a[u])}n.Identify=o;var c=function(){this._q=[]
;return this}
;var l=["setProductId","setQuantity","setPrice","setRevenueType","setEventProperties"]
;for(var p=0;p<l.length;p++){s(c,l[p])}n.Revenue=c
;var d=["init","logEvent","logRevenue","setUserId","setUserProperties","setOptOut","setVersionName","setDomain","setDeviceId","setGlobalUserProperties","identify","clearUserProperties","setGroup","logRevenueV2","regenerateDeviceId","logEventWithTimestamp","logEventWithGroups","setSessionId"]
;function v(e){function t(t){e[t]=function(){
e._q.push([t].concat(Array.prototype.slice.call(arguments,0)))}}
for(var n=0;n<d.length;n++){t(d[n])}}v(n);n.getInstance=function(e){
e=(!e||e.length===0?"$default_instance":e).toLowerCase()
;if(!n._iq.hasOwnProperty(e)){n._iq[e]={_q:[]};v(n._iq[e])}return n._iq[e]}
;e.amplitude=n})(window,document);
amplitude.getInstance().init("AMPLITUDE_KEY");
</script>
</head>
<body>
<!-- Display a message if JS has been disabled on the browser. -->
<noscript>If you're seeing this message, that means <strong>JavaScript has been disabled on your browser</strong>,
please <strong>enable JS</strong> to make this app work.
</noscript>
<!-- The app hooks into this div -->
<div id="app"></div>
<div id="message-container" style="display: none;" class="st-alert"></div>
<div id="connection-status" style="display: none;">
<div>
<span class="fa fa-circle margin-right-16" style="color: red;"></span>
<span>You are offline</span>
</div>
</div>
<div id="progress-bar-container">
<div id="progress-bar"></div>
</div>
<!-- A lot of magic happens in this file. HtmlWebpackPlugin automatically includes all assets (e.g. bundle.js, main.css) with the correct HTML tags, which is why they are missing in this HTML file. Don't add any assets here! (Check out webpackconfig.js if you want to know more) -->
</body>
</html>
To install bootstrap use the following npm command, in your react app.
npm install --save bootstrap
or
npm install --save bootstrap#latest
Once the bootstrap installation is complete. Then add the following import statement to index.js file.
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
or
import 'bootstrap/dist/css/bootstrap.min.css';
For font awesome please refer How to include a Font Awesome icon in React's render(). Someone has posted in stackoverflow.
If you installed Bootstrap using npm install:
Remove <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css" /> from your index.html file.
Then, import the Bootstrap CSS file from node_modules into the root index.js file of your React app:
import 'node_modules/bootstrap/dist/css/bootstrap.min.css';

Cannot get reactjs-admin-lte to work with my reactjs project

I'm pretty new to this react/nodejs/bootstrap affair. I'm trying to make use of the reactjs-adminlte theme for bootstrap. I can get bootstrap widgets to work fine, such as buttons, but having trouble with this theme. The error I get is
React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.
My code is as follows
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap-theme.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<link rel="stylesheet" href="dist/css/AdminLTE.min.css">
<!-- AdminLTE Skins. Choose a skin from the css/skins
folder instead of downloading all of them to reduce the load. -->
<link rel="stylesheet" href="dist/css/skins/_all-skins.min.css">
<title>React App</title>
</head>
<body class="skin-blue sidebar-mini ">
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<script src="/dist/js/vendors.js"></script>
<script src="/dist/js/app.bundle.js"></script>
</body>
</html>
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
App.js
import React, { Component } from 'react';
import './App.css';
import Sidebar from 'adminlte-reactjs';
class App extends Component {
render() {
return (
<div className="App">
<Sidebar>
</Sidebar>
</div>
);
}
}
export default App;
Would love to know why i cant get the Sidebar to display. Its probably something simple that im missing.
Thanks
maybe you should change:
import Sidebar from 'adminlte-reactjs';
to
import {Sidebar} from 'adminlte-reactjs';
or:
import adminlteReactjs from 'adminlte-reactjs';
let Sidebar = adminlteReactjs.Sidebar;
<Sidebar>
</Sidebar>

Resources