How to use bootstrap with reactjs - html

I'm a newbie in React.js and since I began to read documents and tutorials, I am not sure how does Bootstrap work with React.js.
I saw a couple of npm packages such as reactstrap or react-bootstrap, however, I don't get it. The HTML code comes from a method that returns a piece of HTML (like this):
class App extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
If I'm right...
So, my question is either:
Should I add the <link/> or <script/> of Bootstrap into index.html, either into body or into header?
or
Do I have to include Bootstrap from my App.js file and use it from a method?
PS: I am developing for years now but I never did any Javascript/HTML/CSS web, so if you have any advice, thanks in advance!
I need to use the logic of Bootstrap grid in order to realize an HCI
Thanks for any help

To answer your question, both of your suggestions on your questions are correct. You can do it either way.
Include bootstrap CDN in your index.html
You can add bootstrap packages such as React-Bootstrap using npm/yarn and import required components into you App.js
If you do it first way all you need to do is add your Bootstrap CDN in index.html and when you access your class in Javascript, it will be working fine
NOTE: While accessing class in react use className and not class
Here is an example of how you add CDN in your index.html
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({
value: event.target.value
});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<div>
<form onSubmit = {this.handleSubmit} >
<label>
Name:
</label>
<input type = "text" className="form-control"
value = {this.state.value}
onChange = {this.handleChange}/>
<input type = "submit"
value = "Submit" className="btn btn-primary"/>
</form>
</div>
);
}
}
ReactDOM.render( < App / > , document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<div id='root'></div>
EDIT:-
Assuming you installed React according to Official Installation
Use the following file structure
index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/style/style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
<!-- And then your bundled js -->
</head>
<body>
<div class="container"></div>
</body>
<script src="/bundle.js"></script>
</html>
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app'; //Make sure it's the path to your App.js
ReactDOM.render(
<App />
, document.querySelector('.container'));
src/components/app.js
import React, { Component } from 'react';
export default class App extends Component {
render() {
return (
<div>
<form onSubmit = {this.handleSubmit} >
<label>
Name:
</label>
<input type = "text" className="form-control"
value = {this.state.value}
onChange = {this.handleChange}/>
<input type = "submit"
value = "Submit" className="btn btn-primary"/>
</form>
</div>
);
}
}
Check this, it should work.

Related

How to render embedded html with multiple tags in react

I'm embedding a request form. I want to click a button in react to open the form, then add a button to go back/exit. Ive added the HTML tags into index.html but I'm having a hard time with control. I toggle the display: none/block to get it to appear/ disappear which works fine (also have to toggle display for all of the react app so only the form is shown.).
The Html I'm trying to embed has 3 tags. I'm not able to find an answer of how to use dangerouslySetInnerHTML with multiple tags.
I've also just tried to use dangerouslySetInnerHTML twice and just gave the react div the needed reference id. No luck, just a blank white page.
<div id="f6f2802e-49e8-477b-b405-8b2b18dded97"></div>
<link rel="stylesheet" media="screen" href="https://d3ey4dbjkt2f6s.cloudfront.net/assets/external/work_request_embed.css" />
<script src="https://d3ey4dbjkt2f6s.cloudfront.net/assets/static_link/work_request_embed_snippet.js" clienthub_id="f6f2802e-49e8-477b-b405-8b2b18dded97" form_url="https://clienthub.getjobber.com/client_hubs/f6f2802e-49e8-477b-b405-8b2b18dded97/public/work_request/embedded_work_request_form"></script>
12 hours of trying.
(https://codesandbox.io/s/l9qmrwxqzq)
This worked pretty much immediately. Once I found it.
'''
import React from "react";
import ReactDOM from "react-dom";
import { Helmet } from "react-helmet";
import "./styles.css";
function App() {
return (
<div className="App">
<h1>Check if Helmet works as expected with script tags</h1>
<p>Check console output - you will see $ is undefined</p>
<Helmet>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"
/>
<script>
{`
console.log('Test', typeof $);
`}
</script>
</Helmet>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
'''
My final product
'''
import React from "react";
import { Helmet } from "react-helmet";
export default class Jobber extends React.Component {
render() {
return (
<div className="Application" id="f6f2802e-49e8-477b-b405-8b2b18dded97">
<Helmet>
<div id="f6f2802e-49e8-477b-b405-8b2b18dded97"></div>
<link
rel="stylesheet"
media="screen"
href="https://d3ey4dbjkt2f6s.cloudfront.net/assets/external/work_request_embed.css"
/>
<script
src="https://d3ey4dbjkt2f6s.cloudfront.net/assets/static_link/work_request_embed_snippet.js" clienthub_id="f6f2802e-49e8-477b-b405-8b2b18dded97" form_url="https://clienthub.getjobber.com/client_hubs/f6f2802e-49e8-477b-b405-8b2b18dded97/public/work_request/embedded_work_request_form"
/>
</Helmet>
</div>
);
}
}
'''

Importing React component from custom component library into HTML

I created a test react component library (React, Typescript) and am trying to use Rollup to package it up into UMD to I can import the component into an HTML page.
The sample component I created just takes a label prop and colors it orange. Something super simple so complex logic would be taken out of the equation.
React code to render the above text:
import * as React from 'react';
import * as Test from 'react-webpack-demo';
function App() {
return (
<div>
<h1>
{
React.createElement(Test.Brand, { label: 'Brand Label Text'})
}
</h1>
</div>
);
}
export default App;
The above component was packaged via Rollup into CJS format to be imported. I have also attempted to package the same content into UMD so it can be imported into HTML. The full rollup.config.js file is below:
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import typescript from '#rollup/plugin-typescript';
import external from 'rollup-plugin-peer-deps-external';
import packageJson from './package.json';
export default [
{
input: 'src/index.ts',
output: [
{
file: packageJson.main,
format: 'cjs',
sourcemap: true
},
{
file: packageJson.module,
format: 'umd',
name: 'Test',
sourcemap: true
}
],
plugins: [
resolve(),
babel({
exclude: 'node_modules/**',
presets: [
'#babel/preset-react',
'#babel/preset-typescript'
]
}),
external(),
commonjs(),
typescript({ tsconfig: './tsconfig.json' })
],
external: [
...Object.keys(packageJson.dependencies || {}),
...Object.keys(packageJson.peerDependencies || {})
]
}
]
I then attempt to import the newly packaged UMD file into my HTML page and render it into a DOM element as such:
<html lang="en-US">
<head>
<title>Test</title>
<meta charset="utf-8" />
<script src="./react-webpack-demo/dist/umd/index.js" crossorigin></script>
<script src="https://unpkg.com/react#17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#17/umd/react-dom.development.js" crossorigin></script>
</head>
<body>
<h1>Testing rollup in plain HTML</h1>
<hr />
<div id='brand-test'></div>
<script>
const el = React.createElement;
const domContainer = document.getElementById('brand-test');
ReactDOM.render(el(
Test.Brand,
{
label: 'Demo works!'
}
), domContainer);
</script>
</body>
</html>
But I get the following error:
The above error occurred in the component:
Brand#file:///Users/jacorbello/repos/temp/react-webpack-demo/dist/umd/index.js:33:1
Uncaught TypeError: React__namespace.createElement is not a function
Brand Brand.tsx:8
React 17
test.html:20 Brand.tsx:8:11
Any help would be greatly appreciated here.
Thanks in advance for your time!
Seems like the script tag is in incorrect order. Your library needs React to be imported before it's script can be executed.
Just fix the order to get it working
<script src="https://unpkg.com/react#17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#17/umd/react-dom.development.js" crossorigin></script>
<script src="./react-webpack-demo/dist/umd/index.js" crossorigin></script>

the out put of code doesn't change after change in code

I started learning react by writhing this simple code. but it shows me different output in the browser I mean my previous example. I refresh it many times but noting has changed. I write code in visual studio code.
I write this code as App.js
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
header: "Header from state...",
content: "Content from state..."
}
}
render() {
return (
<div>
<h1>{this.state.header}</h1>
<h2>{this.state.content}</h2>
</div>
);
}
}
export default App;
and this as main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
This will produce the following result.
this as index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<link rel="shortcut icon" href="">
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id = "app">
</div>
<script src="build/bundle.js"></script>
</body>
</html>

Error: Argument 'TodoListController' is not a function, got undefined

Please please help!!!
I have simple program but keep getting error. I dont know if i have to define any .js file in manifest.angular as well??
i have seen people sharing examples from old angularjs. so please help. I have got assignment to do. Thanks
todo.js
angular.module('todoApp', [])
.controller('TodoListController', function () {
var todoList = this;
todoList.todos = [
{ text: 'learn AngularJS', done: true },
{ text: 'build an AngularJS app', done: false }];
todoList.addTodo = function () {
todoList.todos.push({ text: todoList.todoText, done: false });
todoList.todoText = '';
};
todoList.remaining = function () {
var count = 0;
angular.forEach(todoList.todos, function (todo) {
count += todo.done ? 0 : 1;
});
return count;
};
todoList.archive = function () {
var oldTodos = todoList.todos;
todoList.todos = [];
angular.forEach(oldTodos, function (todo) {
if (!todo.done) todoList.todos.push(todo);
});
};
});
index.html:
<!doctype html>
<html ng-app="todoApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<script src="/App_Plugins/TheDashboard/backoffice/HomeDashboard/todo.js"></script>
<link rel="stylesheet" href="/App_Plugins/TheDashboard/backoffice/HomeDashboard/todo.css">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.0.4/css/bootstrap-combined.min.css">
</head>
<body>
<h2>Todo</h2>
<div ng-controller="TodoListController as todoList">
<span>{{todoList.remaining()}} of {{todoList.todos.length}} remaining</span>
[ archive ]
<ul class="unstyled">
<li ng-repeat="todo in todoList.todos">
<label class="checkbox">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</label>
</li>
</ul>
<form ng-submit="todoList.addTodo()">
<input type="text" ng-model="todoList.todoText" size="30"
placeholder="add new todo here">
<input class="btn-primary" type="submit" value="add">
</form>
</div>
</body>
</html>
Blockquote
Console Error:
jquery.min.js?cdv=1:4 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
angular.min.js?cdv=1:63 Error: Argument 'TodoListController' is not a function, got undefined
WARNING: Tried to load angular more than once.
angular.js:34191 Uncaught TypeError: window.angular.$$csp is not a function
at angular.js:34191
Blockquote
This will happen in Umbraco when you try and bootstrap two angular modules. Umbraco has the main parent module that you will then want to bootstrap your application separately. If you don't want to do this you can just reference the Umbraco module.
angular.module("umbraco") instead of angular.module('todoApp', []).
Here is a good reference to get started just building property editors https://our.umbraco.org/documentation/Tutorials/Creating-a-Property-Editor/.

I don't see the expected view in angular JS, maybe binding issue?

So I am trying to build the simplest Angular JS application and no idea what I am doing wrong.
It is made of 4 files:
index.html - which I use like a layout to display main.html
app1.js - used for defining simple routing rules like /main should redirect to main.html in combination with MainController; when it doesn't find a valid path, revert to a default which equals the previous path
MainController.js - I just have some timer functions here
main.html - displays a search button and search textbox
For some reason, I can't see mainvtemplate from my index.html which should redirect me to /main.
Here is the code:
index.html file
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<script data-require="angular.js#*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<script data-require="angular-route#*" data-semver="1.2.14" src="http://code.angularjs.org/1.2.14/angular-route.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="app.js"></script>
<script src="MainController.js"></script>
</head>
<body>
<h1>Github Viewer</h1>
<div ng-view></div>
</body>
</html>
the app1.js
(function(){
var app = angular.module("githubViewer", ["ngRoute"]);
app.config(function($routeProvider){
$routeProvider
.when("/main", {
templateUrl: "main.html",
controller: "MainController"
})
.otherwise({redirectTo:"/main"});
});
}());
the main.html file:
<div>
{{ countdown }}
<form name="searchUser" ng-submit="search(username)">
<input type="search" required="" ng-model="username" />
<input type="submit" value="Search" />
</form>
</div>
You may ignore the countdown, this is a timer created in MainController.js. I render its simplified logic:
(function() {
var app = angular.module("githubViewer");
var MainController = function($scope, $interval, $location) {
$scope.search = function(username) {
if(countdownInterval) {
$interval.cancel(countdownInterval);
$scope.countdown = null;
}
$location.path("/user/" + username);
};
$scope.countdown = 5;
};
app.controller("MainController", MainController);
}());
Isn't weird I'm not able to see the search button and search textbox? Maybe I am missing sth really obvious here.
in your index.html
<script src="app.js"></script>
replace with
<script src="app1.js"></script>
main.html
<div ng-app="githubViewer" ng-controller="MainController ">// add ng app ang nd cntroller
{{ countdown }}
<form name="searchUser" ng-submit="search(username)">
<input type="search" required="" ng-model="username" />
<input type="submit" value="Search" />
</form>
</div>