i am working on reactjs in which i want to use bootstrap 4 data table. (Link: https://datatables.net/examples/styling/bootstrap4). i have imported the required js and css into the application but bootstrap 4 datatable pagination is not working as expectation. Following are the code and screenshort of the output:
enter image description here
index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>Hailo Web Portal</title>
<!-- Favicon icon -->
<link rel="icon" href="assets/images/favicon.ico" type="image/x-icon">
<!-- fontawesome icon -->
<link rel="stylesheet" href="assets/fonts/fontawesome/css/fontawesome-all.min.css">
<!-- animation css -->
<link rel="stylesheet" href="assets/plugins/animation/css/animate.min.css">
<!-- vendor css -->
<link rel="stylesheet" href="assets/css/style.css">
<!-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" > -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">
</head>
<body>
<div id = "app"></div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script src="assets/js/vendor-all.min.js"></script>
<!-- <script src="./assets/js/vendor-all.min.js"></script> -->
<script src="assets/plugins/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/js/pcoded.min.js"></script>
<script src = 'index_bundle.js'></script>
<script>
$(document).ready(function() {
$('#example').DataTable();
});
</script>
</body>
</html>
main.js
/*import $ from 'jquery';
import Popper from 'popper.js'; */
/*
import '../node_modules/bootstrap/dist/js/bootstrap.bundle.min'; */
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App.js';
import 'bootstrap';
require('bootstrap/dist/css/bootstrap.css');
ReactDOM.render(<BrowserRouter><App /></BrowserRouter>,document.getElementById('app'));
login.js
import React, { Component } from "react";
import { Link } from "react-router-dom";
import "./Login.css";
import BackgroundImage from "../assets/backgroundImage.png";
/* const emailRegex = RegExp(/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/); */
const emailRegex = RegExp(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/);
const formValid = ({ formErrors, ...rest }) => {
console.log("formErrors=====>", formErrors);
console.log("...rest========>", rest);
let valid = true;
Object.values(formErrors).forEach(val => {
console.log("val--->", val);
val.length > 0 && (valid = false);
});
Object.values(rest).forEach(val => {
val === null && (valid = false);
});
console.log("valid---->", valid);
return valid;
};
const bgimage = {
backgroundImage: `url(${BackgroundImage})`
};
class Login extends Component {
_isMounted = false;
constructor(props) {
super(props);
this.state = {
email: null,
password: null,
formErrors: {
email: "",
password: ""
},
userLists: []
};
this.getAllUsersLists = this.getAllUsersLists.bind(this);
}
componentDidMount() {
this._isMounted = true;
this.getAllUsersLists();
}
componentWillUnmount() {
this._isMounted = false;
}
getAllUsersLists = () => {
const url = "http://192.168.15.149" + ":9001" + "/getAllRoles";
const options = {
method: "GET"
};
fetch(url, options)
.then(results => results.json())
.then(
data => {
if (data.status == "Failure") {
if (this._isMounted) {
this.setState({ userLists: [] });
}
} else {
if (this._isMounted) {
this.setState({
userLists: data
});
}
}
},
error => {
if (this._isMounted) {
this.setState({ userLists: [] });
}
}
);
};
render() {
const { formErrors } = this.state;
return (
<div>
<h1>Test</h1>
<table id="example" className="table table-striped table-bordered" style={{ width: "100%" }}>
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{this.state.userLists.map((ul, index) => (
<tr key={ul.id} id={index+1}>
<td>{ul.role_name}</td>
<td>{ul.description}</td>
<td>{ul.status}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
export default Login;
Any help is appreciated. Thanks in advance.
I would suggest you to use react-bootstrap-table-next
you can try demo and follow the docs for more functionallity and much more easy to customised for the react you can try
try it:
npm install --save datatables.net-dt
In your root component you need import this dependences:
import "datatables.net-dt/js/dataTables.dataTables"
import "datatables.net-dt/css/jquery.dataTables.min.css"
so you can load your table.
componentDidMount() {
$(document).ready(function () {
$('#myTable').DataTable();
});
}
this work for me.
Related
I am trying to make a contact-manager-app from a YouTube video:
https://www.youtube.com/watch?v=0riHps91AzE&lc=Ugybk5M3ofjHsO8uHjd4AaABAg.9WHwkOL6qXV9WJu89p6VTV
Every time, I enter the inputs and click Add, the following error pops-up:
the screen-shot of the main page
I also get "6 moderate severity vulnerabilities" while downloading uuidv4. ( Put just in case, if it might help )
Also got "Module not found: Error: Can't resolve 'util' in 'C:\Users\loki\OneDrive\Desktop\ReactJS-YouTube\contact-app\node_modules\uuidv4\build\lib"
Here are all my files:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="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="%PUBLIC_URL%/logo192.png" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" integrity="sha512-8bHTC73gkZ7rZ7vpqUQThUDhqcNFyYi2xgDgPDHc+GXVGHXq+xPjynxIopALmOPqzo9JZj0k6OqqewdGO3EsrQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
App.js
import React, { useState, useEffect } from "react";
import { uuid } from "uuidv4";
import "./App.css";
import Header from "./Header";
import AddContact from "./AddContact";
import ContactList from "./ContactList";
function App() {
const LOCAL_STORAGE_KEY = "contacts";
const [contacts, setContacts] = useState([]);
const addContactHandler = (contact) => {
console.log(contact);
setContacts([...contacts, { id: uuid(), ...contact }]);
};
const removeContactHandler = (id) => {
const newContactList = contacts.filter((contact) => {
return contact.id !== id;
});
setContacts(newContactList);
};
useEffect(() => {
const retriveContacts = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
if (retriveContacts) setContacts(retriveContacts);
}, []);
useEffect(() => {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
}, [contacts]);
return (
<div className="ui container">
<Header />
<AddContact addContactHandler={addContactHandler} />
<ContactList contacts={contacts} getContactId={removeContactHandler} />
</div>
);
}
export default App;
ContactList.js
import React from "react";
import ContactCard from "./ContactCard";
const ContactList = (props) => {
console.log(props);
const deleteContactHandler = (id) => {
props.getContactId(id);
};
const renderContactList = props.contacts.map((contact) => {
return(
<ContactCard contact={contact} clickHandler = { deleteContactHandler } key = { contact.id}/>
);
})
return(
<div className="ui celled list">
{renderContactList}
</div>
);
}
export default ContactList;
ContactCard.js
import React from "react";
import user from "../images/user.jpg";
const CardContact = (props) => {
const {id, name, email} = props.contact;
return(
<div className="item">
<img className="ui avatar image" src={user} alt="user" />
<div className="content">
<div className="header">{name}</div>
<div>{email}</div>
</div>
<i className="trash alternate outline icon"
style={{color:"red",marginTop:"7px"}}
onClick={() => props.clickHandler(id)}>
</i>
</div>
);
};
export default CardContact;
AddContact.js
import React from "react";
class AddContact extends React.Component {
state = {
name: "",
email: "",
};
add = (e) => {
e.preventDefault();
if (this.state.name === "" || this.state.email === "") {
alert("ALl the fields are mandatory!");
return;
}
this.props.addContactHandler(this.state);
this.setState({ name: "", email: "" });
};
render() {
return (
<div className="ui main">
<h2>Add Contact</h2>
<form className="ui form" onSubmit={this.add}>
<div className="field">
<label>Name</label>
<input
type="text"
name="name"
placeholder="Name"
value={this.state.name}
onChange={(e) => this.setState({ name: e.target.value })}
/>
</div>
<div className="field">
<label>Email</label>
<input
type="text"
name="email"
placeholder="Email"
value={this.state.email}
onChange={(e) => this.setState({ email: e.target.value })}
/>
</div>
<button className="ui button blue">Add</button>
</form>
</div>
);
}
}
export default AddContact;
From the uuidv4 npm page:
Most of the functionality of uuidv4 module is already included in uuid since version 8.3.0, so most of the functions of uuidv4 module have already been marked as deprecated.
So, importing uuidv4 module in your App.js is causing this error.
You can upgrade to the latest version of uuid library to get rid of this error.
Run these commands in the terminal in your project directory.
npm uninstall uuidv4
npm install uuid
And now, in App.js import uuid module instead of uuidv4
import { v4 as uuid } from 'uuid';
And now, you can use uuid() function to create UUIDs
To check more about uuid, you can see there documentation: https://github.com/uuidjs/uuid#quickstart
In your App.js:
On each useEffect (page renders) you are calling setContract , on useEffect below you are watching that contract as dependency , so it's rendering when contract is changing
useEffect(() => {
const retriveContacts = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
if (retriveContacts) setContacts(retriveContacts);
}, []);
useEffect(() => {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts));
}, [contacts]);
I am following the Emailjs tutorial found here - https://www.emailjs.com/docs/tutorial/creating-contact-form/.
I am getting these error lines when the web page fails to compile:
Failed to compile./src/components/SwatForm.js
Line 42:29: 'emailjs' is not defined no-undef
Line 52:33: 'emailjs' is not defined no-undef
Line 64:33: 'emailjs' is not defined no-undef
Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed.
Here is the actual code from the tutorial in my react application.
import React, { Component } from 'react';
import { Container, Row, Col, Button, NavLink } from 'reactstrap';
import { Link } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import groupPicture from "../church2019.jpg";
import Image from 'react-bootstrap/Image';
import './Site.css';
export class SwatForm extends Component {
static displayName = SwatForm.name;
constructor(props) {
super(props);
this.state = {
name: "",
email: "",
feedback: "",
};
}
handleInputChange(event) {
event.preventDefault();
const target = event.target;
const name = target.name;
const value = target.value;
this.setState({ [name]: value });
}
render() {
return (
<Container>
<html>
<head>
<title>Contact Form</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com#2/dist/email.min.js"></script>
<script type="text/javascript">
(function() {
// https://dashboard.emailjs.com/admin/integration
emailjs.init('user_0rJrw0xxhrNqhld3WUc3q')
})();
</script>
<script type="text/javascript">
window.onload = function() {
document.getElementById('contact-form').addEventListener('submit', function (event) {
event.preventDefault();
// generate a five digit number for the contact_number variable
this.contact_number.value = Math.random() * 100000 | 0;
// these IDs from the previous steps
emailjs.sendForm('contact_service', 'contact_form', this)
.then(function () {
console.log('SUCCESS!');
}, function (error) {
console.log('FAILED...', error);
});
})
}
</script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com#2/dist/email.min.js"></script>
<script type="text/javascript">
(function() {
emailjs.init("user_0rJrw0xxhrNqhld3WUc3q")
})();
</script>
</head>
<form id="contact-form">
<input type="hidden" name="contact_number" />
<label>Name</label>
<input type="text" name="user_name" />
<label>Email</label>
<input type="email" name="user_email" />
<label>Message</label>
<textarea name="message"></textarea>
<input type="submit" value="Send" />
</form>
</html>
</Container>
);
}
}
There is a package for the use of this library. I think you should use it.
https://www.npmjs.com/package/emailjs-com
https://www.emailjs.com/docs/examples/reactjs/
I have a form to add a category. I expect that when clicking on the add button, there is a notification showing in the corner screen if the input is empty. My idea is returning a Çomponent( or function) contains a toast in handleAddNewCategory() but it's not showing. I know that the library react-bootstrap can do showing toast like this
handleAddNewCategory(){
if(condition)
return toastr.info("message",...);
}
but I don't want to use it for now. Can anyone give me a solution to solve this with using only bootstrap. I'm totally new to Reactjs.
This is some minimal file:
import React, { Component } from "react";
import AddNewCategory from "./AddNewCategory";
import Notification from "./Notification";
class CategoryList extends Component {
constructor(props) {
super(props);
this.state = {
categoryNameInput: "",
categoryDescriptionInput: "",
};
}
...
handleAddNewCategory = () => {
const { categoryNameInput, categoryDescriptionInput } = this.state;
if (categoryNameInput.trim() === "") {
return <Notification message="Please enter category name" />;
}
if (categoryDescriptionInput.trim() === "") {
return <Notification message="Please enter category description" />;
}
};
render() {
return (
<div className="container">
...
<AddNewCategory handleAddNewCategory={this.handleAddNewCategory} />
...
</div>
);
}
}
export default CategoryList;
Notification component
import React, { Component } from "react";
class Notification extends Component {
render() {
const myStyle = {
zIndex: "1001",
position: "absolute",
top: "10px",
right: "10px",
};
return (
<div className="toast col-2" style={myStyle} data-autohide="false">
<div className="toast-header">
<strong className="mr-auto text-primary">Notice</strong>
</div>
<div className="toast-body">{this.props.message}</div>
</div>
);
}
}
export default Notification;
index.html
<!DOCTYPE html>
<html lang="en">
<head>
...
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$('.toast').toast('show');
});
</script>
</body>
</html>
don't use jquery to show the toast it's not the best practice and instead of conditionally rendering the component what you can do is. just render it ones and then controlled its visibility.
follow the below code:-
Notification component
import React, { Component } from "react";
class Notification extends Component {
render() {
const myStyle = {
zIndex: "1001",
position: "absolute",
top: "10px",
right: "10px",
};
return (
<div hidden={this.props.showToast} className="toast col-2" style={myStyle} data-autohide="false">
<div className="toast-header">
<strong className="mr-auto text-primary">Notice</strong>
</div>
<div className="toast-body">{this.props.message}</div>
</div>
);
}
}
export default Notification;
Notification component usage :-
class CategoryList extends Component {
constructor(props) {
super(props);
this.state = {
categoryNameInput: "",
categoryDescriptionInput: "",
toastMessage:'',
showToast:false
};
}
...
handleAddNewCategory = () => {
const { categoryNameInput, categoryDescriptionInput } = this.state;
if (categoryNameInput.trim() === "") {
this.setState({
toastMessage:'Please enter category name',
showToast:true
})
}
if (categoryDescriptionInput.trim() === "") {
this.setState({
toastMessage:'Please enter category name',
showToast:true
})
}
};
render() {
return (
<div className="container">
<Notification message={this.state.toastMessage} showToast={this.state.showToast}/>;
...
<AddNewCategory handleAddNewCategory={this.handleAddNewCategory} />
...
</div>
);
}
}
export default CategoryList;
here what i do is i initialise the boolean in state and enable it so that toast will be visible and i pass it directly throw props so that whenever your message and boolean changes it automatically reflects in your notification controller.
and to remove the toast just set {showToast} to false whenever you want. and remove the jquery part from your code
I'm using a CMS to build interfaces and need React JS to integrate into the system via CDN links. It gives me an error when trying to load some components. Do I have to explicitly keep loading components or is there some other way? Im using the following links:
`
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="react-container"></div>
<script type="text/babel">
class Note extends React.Component {
constructor(props) {
super(props)
this.state = {
checked: true,
activePage: 1
}
this.handleCheck = this.handleCheck.bind(this)
}
handleCheck() {
this.setState({
checked: !this.state.checked
})
}
handlePageChange(pageNumber) {
this.setState({activePage: pageNumber});
}
render() {
var msg
if(this.state.checked) {
msg = "checked"
} else {
msg = "not checked"
}
return (
<div>
<input type="checkbox"
onChange={this.handleCheck}
defaultChecked={this.state.checked}/>
<Pagination
hideNavigation
activePage={this.state.activePage}
itemsCountPerPage={10}
totalItemsCount={450}
pageRangeDisplayed={10}
onChange={this.handlePageChange}
/>
</div>
)
}
}
ReactDOM.render(
<Note />,
document.getElementById('react-container')
)
</script>
`
Also, sometimes it gives me out of memory error.
Browser hangs.
Below is an example of how to use cdn for reactjs. Hope it helps :)
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script type="text/babel">
class Greeting extends React.Component {
render() {
const name = 'Johnson';
return (<p>Hello world {name}</p>);
}
}
ReactDOM.render(
<Greeting />,
document.getElementById('root')
);
</script>
I'm stuck with this codes,
index.html
<!doctype html>
<html lang="en">
<head>
<title>React Redux Starter Kit</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
<div id="root" style="height: 100%"></div>
<div id="demo"></div>
</body>
</html>
Counter.js
import React from 'react'
import {core as Core} from 'zingchart-react'
export const Counter = React.createClass({
render () {
var myConfig = {
type: "bar",
series : [
{
values : [35,42,67,89,25,34,67,85,90.99]
}
]
};
return(
<div>Hello
<Core id="myChart" height="300" width="600" data={myConfig} />
</div>
)
}
})
export default Counter
main.js
import React from 'react'
import ReactDOM from 'react-dom'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import { useRouterHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
import createStore from './store/createStore'
import AppContainer from './containers/AppContainer'
import Counter from './components/Counter/Counter'
ReactDOM.render(<Counter/>, document.querySelector('#demo'));
// ========================================================
// Browser History Setup
// ========================================================
const browserHistory = useRouterHistory(createBrowserHistory)({
basename: __BASENAME__
})
// ========================================================
// Store and History Instantiation
// ========================================================
const initialState = window.___INITIAL_STATE__
const store = createStore(initialState, browserHistory)
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: (state) => state.router
})
if (__DEBUG__) {
if (window.devToolsExtension) {
window.devToolsExtension.open()
}
}
const MOUNT_NODE = document.getElementById('root')
let render = (routerKey = null) => {
const routes = require('./routes/index').default(store)
ReactDOM.render(
<AppContainer
store={store}
history={history}
routes={routes}
routerKey={routerKey}
/>,
MOUNT_NODE
)
}
if (__DEV__ && module.hot) {
const renderApp = render
const renderError = (error) => {
const RedBox = require('redbox-react')
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
}
render = () => {
try {
renderApp(Math.random())
} catch (error) {
renderError(error)
}
}
module.hot.accept(['./routes/index'], () => render())
}
render()
I am using react-redux starter kit - https://github.com/davezuko/react-redux-starter-kit, I'm getting this error, please help me out.
ERROR: Cannot read property '__reactAutoBindMap' of undefined
This is the es6 way of writing your component:
import React from 'react';
import {core as Core} from 'zingchart-react';
class Counter extends React.Component {
render () {
var myConfig = {
type: "bar",
series : [
{
values : [35,42,67,89,25,34,67,85]
}
]
};
return (
<div>Hello
<Core id="myChart" height="300" width="600" data={myConfig} />
</div>
)
}
}
export default Counter;
and to render it,
ReactDOM.render(<Counter />, document.getElementById('some_div'));
core is not a valid name for a React Component. React Components must start with an upper case letter, that is how React distinguish between components and HTML tags.
So your code should look like this
import React from 'react'
import {core as Core} from 'zingchart-react'
export const Counter = React.createClass({
render () {
var myConfig = {
type: "bar",
series : [
{
values : [35,42,67,89,25,34,67,85]
}
]
};
return (
<div>Hello
<Core id="myChart" height="300" width="600" data={myConfig} />
</div>
)
}
})
export default Counter
working example