How to use google translator with flags in nextjs - javascript

I am new in Reactjs and trying to integrate "google translator with flags",I have following code
which is working fine (html + javascript code) and giving me exactly output as i want but how can i use this
code in "nextjs/react" (index.js page)?
<html>
<head id="Head1" runat="server">
<title>Google Translation</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.2/css/bootstrap-select.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.5.0/css/flag-icon.min.css" rel="stylesheet" type="text/css" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="google_translate_element" style="display: none;"></div>
<select class="selectpicker" data-width="fit" onchange="translateLanguage(this.value);">
<option data-content='<span class="flag-icon flag-icon-us"></span> English' value="English">English</option>
<option data-content='<span class="flag-icon flag-icon-fr"></span> French' value="French">French</option>
<option data-content='<span class="flag-icon flag-icon-es"></span> Spanish' value="Spanish">Spanish</option>
</select>
<div>
This is just a table.
</div>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.2/js/bootstrap-select.min.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" type="text/javascript"></script>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({ pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE, autoDisplay: false }, 'google_translate_element');
}
function translateLanguage(lang) {
googleTranslateElementInit();
var $frame = $('.goog-te-menu-frame:first');
//alert('value is ' +lang);
if (!$frame.size()) {
alert("Error: Could not find Google translate frame.");
return false;
}
$frame.contents().find('.goog-te-menu2-item span.text:contains(' + lang + ')').get(0).click();
return false;
}
$(function(){
$('.selectpicker').selectpicker();
});
</script>
</body>
</html>
I tried but giving me following error
"Hydration failed because the initial UI does not match what was rendered on the server"

Update answer:
import React, { useEffect, useState, useRef } from "react";
export default function IndexPage() {
function translateLanguage(lang) {
googleTranslateElementInit();
const frame = document.getElementsByClassName("goog-te-menu-frame")[0];
if (!frame) return;
const items = frame.contentDocument.documentElement.querySelectorAll(
".goog-te-menu2-item"
);
items.forEach((element) => {
if (lang == element.getElementsByTagName("span")[1].innerText)
element.click();
});
return false;
}
function googleTranslateElementInit() {
if (!google) return;
new (google.translate.TranslateElement)(
{
pageLanguage: "en",
layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
autoDisplay: false
},
"google_translate_element"
);
}
useEffect(() => {
let script = document.createElement("script");
script.src = `https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit`;
document.body.insertBefore(script, document.body.childNodes[0]);
}, []);
return (
<div>
<div id="google_translate_element" style={{ display: "none" }} />
<CustomSelect onChange={translateLanguage} />
<div>This is just a table.</div>
</div>
);
}
const CustomSelect = ({ onChange }) => {
const [lang, setLang] = useState(LANGS[0]);
const [isShow, setIsShow] = useState(false);
const ref = useRef(null);
useClickOutside(ref, () => setIsShow(false));
return (
<div className="w-24 cursor-pointer relative">
<div onClick={() => setIsShow(true)} ref={ref}>
<span className={`flag-icon ${lang.icon}`} /> {` ${lang.name}`}
</div>
<div
className={`border border-b-0 absolute top-6 left-0 bg-white ${!isShow && "hidden"
}`}
>
{LANGS.map((lang, index) => (
<div
key={index}
className="border-b"
onClick={() => {
setLang(lang);
onChange(lang);
}}
>
<span className={`flag-icon ${lang.icon}`} />
{` ${lang.name}`}
</div>
))}
</div>
</div>
);
};
const LANGS = [
{
name: "English",
icon: "flag-icon-us"
},
{
name: "French",
icon: "flag-icon-fr"
},
{ name: "Spanish", icon: "flag-icon-es" }
];
const useClickOutside = (ref, callback) => {
const handleClick = (e) => {
if (ref.current && !ref.current.contains(e.target)) {
callback(e);
}
};
React.useEffect(() => {
document.addEventListener("click", handleClick);
return () => {
document.removeEventListener("click", handleClick);
};
});
};
You can check in codesandbox

Related

Uncaught ReferenceError: function is not defined eventhough scope seems right Javascript

I got an "Uncaught ReferenceError". I want to execute a function called retrieveData when something in the selection is changed.
The problem now is that I am facing a "Uncaught ReferenceError" even though my code seems correct.
I know that it has probably something to do with the scope or cache. But I can't really figure it out.
There are two files: HTML and cart.js.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<link rel="icon" type="image/x-icon" href="/images/logo.png">
<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=Ubuntu&display=swap" rel="stylesheet">
<script src="https://smtpjs.com/v3/smtp.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<title>Shop</title>
</head>
<body>
<nav>
<img src="./images/logo.png" alt="LOGO">
SHOP
WARENKORB
</nav>
<section class="hero-section">
<div class="hero-content-container">
<div class="shop_with_us">
<h1>Kaufe bei uns ein..!</h1>
Suche unsere Produkte!s
</div>
<div>
</div>
</div>
</section>
<h1 class="text-align-center m-y-30">Produkte im Warenkorb</h1>
<h3 class="text-align-center" id="total_price_container">Gesamter Preis <span id="total_price"></span>€</h3>
<section id="products_section" class="products_section">
</section>
<section id="no-products_section" class="no-products_section" style="display: none;">
<h1 class="text-align-center">Keine Produkte im Warenkorb!</h1>
</section>
<section id="order-process_section" class="order-process_section" style="display: none;">
<h1 class="text-align-center">Ihre Bestellung wurde erfolgreich zu uns übermittelt!</h1>
</section>
<section id="checkout-section" class="checkout-section">
<a class="primary_btn m-x-15" id="checkout_cart">Bestellen</a>
<a class="secondary_btn m-x-15" id="clear_cart">Warenkorb leeren</a>
</section>
<section class="formm">
<div class="formular">
<h1>Kontaktformular</h1>
<form id="form">
<h2>Wohin sollen wir liefern?</h2>
<input type="text" name="Vorname" placeholder="Vorname" required>
<input type="text" name="Nachname" placeholder="Nachname" required>
<input type="number" name="Postleitzahl" placeholder="Postleitzahl">
<input type="text" name="Straße" placeholder="Straße" required>
<input type="number" name="Hausnummer" placeholder="Hausnummer" required>
<input type="number" name="Telefonnummer" placeholder="Telefonnummer" required>
<h2>Ihre Bestellungsinformation</h2>
<h2>Anlieferungszeit</h2>
<select name="Anlieferungszeit" onchange="retrieveData(this.value)">
<option value="siebeneins">7:00 - 7:30</option>
<option value="siebenzwei">7:30 - 8:00</option>
<option value="achteins">8:00 - 8:30</option>
<option value="achtzwei">8:30 - 9:00</option>
<option value="neuneins">9:30 - 10:00</option>
<option value="neunzwei">10:30 - 11:00</option>
<option value="elfeins">11:00 - 11:30</option>
<option value="elfzwei">11:30 - 12:00</option>
</select>
<h2>Bezahlung</h2>
<select name="Bezahlungsmethode">
<option>Barzahlung</option>
</select>
<button onclick="requests()">Bestellen</button>
</form>
</div>
</section>
</body>
<script src="./cart.js" type="module">
</script>
</html>
cart.js:
let productsSection = document.getElementById("products_section");
productsSection.innerHTML = '';
let productHTML = '';
let totalPrice = 0;
let cartItems = JSON.parse(localStorage.getItem('cart'));
if (cartItems && cartItems.length > 0) {
for (let item of cartItems) {
totalPrice = totalPrice + (item.quantity * item.price);
productHTML = productHTML + `
<div class="product-card" data-name="${item.itemName}" data-price="${item.price}" data-id="${item.itemId}">
<div>
<img src="./images/fruits/${item.itemName}.jpg" alt="FRUIT" width="180">
</div>
<h3>
${item.itemName}
</h3>
<div>
Anzahl: ${item.quantity}
</div>
<div>
Preis: ${item.quantity * item.price}€
</div>
</div>
`;
}
document.getElementById("total_price_container").style.display = 'block';
document.getElementById("total_price").innerHTML = totalPrice;
document.getElementById("no-products_section").style.display = 'none';
document.getElementById("checkout-section").style.display = 'flex';
document.getElementById("order-process_section").style.display = 'none';
productsSection.innerHTML = productHTML;
}
else {
document.getElementById("no-products_section").style.display = 'block';
document.getElementById("checkout-section").style.display = 'none';
document.getElementById("total_price_container").style.display = 'none';
}
};
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
window.alert = function() {};
function check() {
const Vorname = document.getElementsByName("Vorname").values;
const Nachname = document.getElementsByName("Nachname").values;
const Postleitzahl = document.getElementsByName("Postleitzahl").values;
const Straße = document.getElementsByName("Straße").values;
const Hausnummer = document.getElementsByName("Hausnummer").values;
const Telefonnummer = document.getElementsByName("Telefonnummer").values;
const local = localStorage;
if (Vorname == "") {
//pass
}
console.log(local)
}
loadCart();
document.getElementById('checkout_cart').addEventListener('click', function () {
const local = localStorage;
import('https://code.jquery.com/jquery-2.2.4.min.js');
$.ajax({
method: 'POST',
url: 'https://formsubmit.co/ajax/semmelbrothers.system#gmail.com',
dataType: 'json',
accepts: 'application/json',
data: {
_cc: "trgdeath#gmail.com",
name: "FormSubmit",
message: window.localStorage.getItem('cart')
},
success: (data) => console.log(data),
error: (err) => console.log(err)
});
console.log(localStorage);
localStorage.removeItem('cart');
document.getElementById("products_section").innerHTML = '';
document.getElementById("order-process_section").style.display = 'block';
document.getElementById("checkout-section").style.display = 'none';
})
document.getElementById('clear_cart').addEventListener('click', function () {
localStorage.removeItem('cart');
loadCart();
})
function retrieveData(str) {
var xhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (parseInt(this.responseText) > 12) {
document.getElementById(str).style.visibility = "hidden";
}
}
};
xhttp.open("GET", "retrievedata.php?q="+str, true);
xhttp.send();
}
Error message:
Uncaught ReferenceError: retrieveData is not defined
onchange https://example.com/cart.html:1
cart.html:1:1
onchange https://example.com/cart.html:1
receiveMessage resource://gre/actors/SelectChild.jsm:272
receiveMessage resource://gre/actors/SelectChild.jsm:475
your script cart.js is a module. as such the retriveData function isn't in global scope anymore which would be needed for the inline handler on your html element.
Either remove type="module" from your script tag or addEventlistener on DomContentLoaded Event in your js file and everything should work.

Caption from alt is not showing up with onClick function

I'm using Bootstrap 4 and I have two JS-functions which I want to work together but I can't figure out how..
The first function is for showing the "alt" as caption below images.
The second function is an onClick function which shows the next image by clicking on the image.
My Problem is that when I activate the onClick function and the next image is shown, the "alt" caption doesn't change.
Here is the part of the code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="row my-row">
<div class="col-md-3 ">
<!--thumbnail container-->
<div class="thumbnailContainer">
</div>
<div class="col-md-9 ">
<!--START MAIN CONTENT-->
<div class="hideMobile">
<div class="d-flex justify-content-center">
<span onclick="this.parentElement.style.display='none'"></span>
<img class="img-fluid img-overlay" id="expandedImg" style="max-height: 80vh;" onClick="nextImage(this)" src="https://images.pexels.com/photos/12233047/pexels-photo-12233047.jpeg?cs=srgb&dl=pexels-chandan-suman-12233047.jpg&fm=jpg">
</div>
<div class="container expandedImgSize d-flex justify-content-center" id="imgtext">
<figcaption style="color: #999999; font-size: 12px;" class="figure-caption">CAPTION
</figcaption>
</div>
</div>
<!--END MAIN CONTENT-->
</div>
<!--col-md-9-->
</div>
</div>
<!--END Wrapper-->
<script type="text/javascript">
// Data
const imagesArr = [{
image: 'https://media.istockphoto.com/photos/stack-of-books-picture-id157482029?b=1&k=20&m=157482029&s=170667a&w=0&h=EVs9M4nx2kPCdIBYMULaSfj75k-wqjEAsaE8GkLwkbw=',
alt: '<br>Test<br>Test1<br>Test1',
},
{
image: 'https://media.istockphoto.com/photos/large-stack-of-papers-on-a-white-background-picture-id178580846?k=20&m=178580846&s=612x612&w=0&h=agODFyEclthiTCyRGMtKoYDGsXRD0GmVpvJnEPhSQws=',
alt: '<br>Test<br>Test2<br>Test2',
},
{
image: 'https://st2.depositphotos.com/2769299/7314/i/450/depositphotos_73146765-stock-photo-a-stack-of-books-on.jpg',
alt: '<br>Test<br>Test3<br>Test3',
},
];
const createImage = (image, alt, index) => {
return `<img src="${image}" alt="${alt}" class="img-thumbnail border-0 img-thumbnail-desktop" onClick="expandingImage(this)" currentimage="${index}"/>`;
};
// Logic
const createImages = (images) => {
let final = '';
for (let i = 0; i < images.length; i++) {
const e = images[i];
final += createImage(e.image, e.alt, i);
}
return final;
}
document.addEventListener("DOMContentLoaded", function() {
console.log('Loaded')
const container = document.querySelector('.thumbnailContainer');
container.innerHTML = createImages(imagesArr)
});
const nextImage = (img) => {
const current = +img.getAttribute('currentimage');
if (current < imagesArr.length - 1) {
img.setAttribute('src', imagesArr[current + 1].image)
img.setAttribute('currentimage', current + 1)
}
}
function expandingImage(imgs) {
const expandImg = document.getElementById("expandedImg");
const imgText = document.getElementById("imgtext");
expandImg.src = imgs.src;
imgText.innerHTML = imgs.alt;
expandImg.setAttribute("currentimage", imgs.getAttribute('currentimage'))
expandImg.parentElement.style.display = "block";
}
</script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
</script>
</body>
</html>

How to import react modules from an HTML file with no npm/webpack

I have a static html file, in which I fetch react like this:
<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/prop-types#15.7.2/prop-types.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
and then I write my javascript like this:
<script type="text/babel">
class App extends React.Component {...}
and initialize it on the page like this:
const domContainer = document.querySelector('#react-container');
ReactDOM.render(<App/>, domContainer);
My question, is how can I use a react component library, such as https://www.npmjs.com/package/react-datepicker ?
I found that it's hosted at https://unpkg.com/react-datetime-picker#2.7.1/dist/DateTimePicker.js but if I add that as a and try to use in my app, it says:
> Uncaught ReferenceError: DateTimePicker is not defined
at App.render (<anonymous>:66:37)
at finishClassComponent (react-dom.development.js:18597)
at updateClassComponent (react-dom.development.js:18550)
at beginWork$1 (react-dom.development.js:20307)
at HTMLUnknownElement.callCallback (react-dom.development.js:330)
at Object.invokeGuardedCallbackDev (react-dom.development.js:379)
at invokeGuardedCallback (react-dom.development.js:434)
at beginWork$$1 (react-dom.development.js:25884)
at performUnitOfWork (react-dom.development.js:24808)
at workLoopSync (react-dom.development.js:24784)
how should I properly import the DateTimePicker?
After fiddling around with react-datepicker, it seems to be missing some core dependencies that aren't available via a CDN. Instead, an alternative would be to be use react-datetime. While it's not as fancy, it does get the job done (with a little bit of tweaking).
Click on the Run Code Snippet button below for a demo.
Demo: Click on the Select Date button to open the date picker, select a date and/or time, then you can either click on the Close button or click outside of the calendar to close the date picker.
.calendar-container {
width: 260px;
}
.container {
padding: 20px;
}
.date-button {
width: 100%;
border-radius: 2px;
}
.form-control {
display: none;
}
.rdtDays, .rdtTime {
border: 1px solid #ebebeb;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<title>React App</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.development.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.development.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react-datetime/3.0.0/react-datetime.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/react-datetime/3.0.0/css/react-datetime.min.css" rel="stylesheet" type="text/css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.2.0/css/uikit.min.css" rel="stylesheet" type="text/css">
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<script type="text/babel">
const { useEffect, useRef, useState, useCallback } = React;
const App = () => {
const wrapperRef = useRef();
const [state, setState]=useState({ date: null, isOpen: false });
const handleDateChange = useCallback(date => setState(prevState => ({ ...prevState, date })),[setState]);
const openCalendar = useCallback(() => setState(prevState => ({ ...prevState, isOpen: !prevState.isOpen })), [setState]);
const handleClickOutside = useCallback(({ target }) => {
if (state.isOpen && wrapperRef && !wrapperRef.current.contains(target)) {
setState(prevState => ({ ...prevState, isOpen: false }));
}
},
[state.isOpen, wrapperRef]);
useEffect(
() => {
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
},
[handleClickOutside]
);
return (
<div className="container">
<div className="calendar-container" ref={wrapperRef}>
<button className="uk-button uk-button-primary date-button" onClick={openCalendar}>{!state.isOpen ? "Select Date" : "Close"}</button>
{ state.isOpen && <Datetime input={false} onChange={handleDateChange}></Datetime>}
</div>
{ state.date && <p>Selected Date: {moment(state.date).format("MM/DD/YYYY hh:mm a")}</p> }
</div>
);
}
ReactDOM.render(<App />,document.getElementById("root"));
</script>
</body>
</html>

How do i delete item from local storage with delegation?

I m trying to make a bookmark app in which when i type the name and address of a website they should appear underneath the form when i click submit button.Also when i click the delete button it should remove item not only from UI but also from local storage.And that s the problem.I have no problem deleting them from UI but when i reload the page they keep showing up.I know it s complicated but if someone s interested i would urge them to pay attention to Store class which deals with storage particulary deleteBookmarkFromStorage() method.
document.getElementById("myForm").addEventListener("submit", saveBookmark);
document.querySelector(".col-lg-12").addEventListener("click", function(e) {
const ui = new UI();
ui.deleteItem(e.target);
Store.deleteBookmarkFromStorage(e.target.parentElement);
ui.showAlert("You deleted a bookmark", "alert alert-success");
e.preventDefault();
});
class Bookmark {
constructor(siteName, siteUrl) {
this.siteName = siteName;
this.siteUrl = siteUrl;
}
}
class UI {
constructor() {
this.siteName = document.getElementById("siteName");
this.siteUrl = document.getElementById("siteUrl");
this.bookmarksResults = document.getElementById("bookmarksResults");
}
showAlert(message, className) {
const div = document.createElement("div");
div.appendChild(document.createTextNode(message));
div.className = className;
const container = document.querySelector(".container");
const bookmarkCard = document.getElementById("bookmarkCard");
container.insertBefore(div, bookmarkCard);
setTimeout(() => {
document.querySelector(".alert").remove();
}, 3000);
}
showBookmark(bookmark) {
const div = document.createElement("div");
div.className = "card-body";
div.innerHTML = `
<h3 class="inline-block">${bookmark.siteName}</h3>
<a class="btn btn-primary" target="_blank"
href=${bookmark.siteUrl}>Visit</a>
<a class="btn btn-danger" href="#">Delete</a>
`;
const results = this.bookmarksResults;
results.appendChild(div);
}
clearInput() {
this.siteName.value = "";
this.siteUrl.value = "";
}
deleteItem(target) {
if (target.className === "btn btn-danger") {
target.parentElement.remove();
}
}
}
class Store {
static getBookmarks() {
let bookmarks;
if (localStorage.getItem("bookmarks") === null) {
bookmarks = [];
} else {
bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
}
return bookmarks;
}
//show bookmarks in UI
static displayBookmarks() {
const bookmarks = Store.getBookmarks();
bookmarks.forEach(function(bookmark) {
const ui = new UI();
ui.showBookmark(bookmark);
});
}
//Add bookmark to storage
static addBookmarkToStorage(bookmark) {
const bookmarks = Store.getBookmarks();
bookmarks.push(bookmark);
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
}
//Delete bookmark from storage
static deleteBookmarkFromStorage() {
const bookmarks = Store.getBookmarks();
bookmarks.forEach(function(bookmark) {
if (bookmark.className === "btn btn-danger") {
bookmarks.splice(index, 1);
}
});
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
}
}
document.addEventListener("DOMContentLoaded", Store.displayBookmarks);
function saveBookmark(e) {
const siteName = document.getElementById("siteName").value;
const siteUrl = document.getElementById("siteUrl").value;
const bookmark = new Bookmark(siteName, siteUrl);
const ui = new UI();
if (siteName === "" || siteUrl === "") {
ui.showAlert("Please fill in all the fields", "alert alert-danger");
} else {
ui.showBookmark(bookmark);
Store.addBookmarkToStorage(bookmark);
ui.showAlert("You added a new bookmark", "alert alert-success");
ui.clearInput();
}
e.preventDefault();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>My JavaScript App</title>
<!--Bootstrap-->
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous"
/>
</head>
<body>
<div class="container">
<h3 class="mt-3 mb-3 text-muted">Bookmarker</h3>
<hr />
<div class="card card-body pt-5 pb-5 mb-3" id="bookmarkCard">
<h2>Bookmark Your Favorite Sites</h2>
<form id="myForm">
<div class="form-group">
<label>Site Name</label>
<input
type="text"
class="form-control"
id="siteName"
placeholder="Website Name"
/>
</div>
<div class="form-group">
<label>Site URL</label>
<input
type="text"
class="form-control"
id="siteUrl"
placeholder="Website URL"
/>
</div>
<button type="submit" class="btn btn-primary " id="submitButton">
Submit
</button>
</form>
</div>
<div class="row marketing">
<div class="col-lg-12">
<div id="bookmarksResults"></div>
</div>
</div>
<footer class="footer">
<p>© 2019 Bookmarker, Inc.</p>
</footer>
</div>
<script
src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"
></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"
></script>
<script src="build/app.bundle.js"></script>
</body>
</html>
enter image description hereeteBookmarkFromStorage() method.
You can try to remove everything from the local storage before writing back the updated object:
localStorage.clear();
Also, check out how it would work with sessionStorage.
I solved it.
//event listener
Store.deleteBookmarkFromStorage( e.target.previousElementSibling.previousElementSibling.textContent
);
//Class Store
static deleteBookmarkFromStorage(siteName) {
const bookmarks = Store.getBookmarks();
bookmarks.forEach(function(bookmark, index) {
if (bookmark.siteName === siteName) {
bookmarks.splice(index, 1);
}
});
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
}

How to update different component textbox value in React js..?

Environment
OS : Windows 7 - 64 bit
Framework : CodeIgniter PHP MVC
JS: React Js
I am having two different components LeftComponent and RightComponent which is merged by MergeLeftRightComponent.
MainApp which is responsible for rendering.
Having textbox in LeftComponent and RightComponent. While changing value in left textbox, i need to update value in right textbox and vice-versa.
How to achieve this..?
Framed this app from the basics of codeofaninja tutorial.
My app sample view
Codes
view.php
<!DOCTYPE html>
<head>
<title>React page</title>
</head>
<body>
<div class='task-container' id='task-container'>
</div>
<!-- react js -->
<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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<!-- react components -->
<script type="text/babel" src="<?php echo base_url('assets/js/components/right.component.js');?>"></script>
<script type="text/babel" src="<?php echo base_url('assets/js/components/left.component.js');?>"></script>
<script type="text/babel" src="<?php echo base_url('assets/js/components/merge.component.js');?>"></script>
<script type="text/babel" src="<?php echo base_url('assets/js/components/main.component.js');?>"></script>
<!-- jQuery library required by bootsrap js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
main.component.js
var MainApp = React.createClass({
render: function(){
var modeComponent = <MergeLeftRightComponent changeAppMode={this.changeAppMode} />;
return modeComponent;
}
});
ReactDOM.render(<MainApp />,document.getElementById('task-container'));
merge.component.js
window.MergeLeftRightComponent = React.createClass({
getInitialState: function() {
return {
inputVal:"",
};
},
changeinputVal: function(e) {
this.setState({
inputVal: e.target.value,
});
},
render: function() {
return (
<div className='task-container'>
<LeftComponent inputVal={this.state.inputVal} onChange={this.changeinputVal}/>
<RightComponent inputVal={this.state.inputVal} onChange={this.changeinputVal}/>
</div>
);
}
});
left.component.js
window.LeftComponent = React.createClass({
getInitialState: function(){
return {
task_name:"Mountain task"
};
},
handleChange: function(e){
this.setState({
inputVal:e.target.value
});
},
render: function() {
return(
<div className="left-box">
<div className="info-container">
<input type="text" className="task-name form-control" value={this.props.task_name} onChange={this.handleChange}/>
</div>
</div>
);
}
});
right.component.js
window.RightComponent = React.createClass({
getInitialState: function(){
return {
task_name:"Mountain task"
};
},
handleChange: function(e){
this.setState({
inputVal:e.target.value
});
},
render: function() {
return(
<div className="right-box">
<div className="info-container">
<input type="text" className="task-name form-control" value={this.props.task_name} onChange={this.handleChange}/>
</div>
</div>
);
}
});
Help me to achieve this.
Thanks in Advance..
in the merge.component.js file you need to bind changeinputVal function
In left.component.js call changeinputVal function at your input function
handleChange: function(e){
this.setState({
inputVal:e.target.value
});
this.props.onChange(e);
},
merge.component.js file
class MergeLeftRightComponent extends React.Component {
constructor(props) {
super(props);
this.changeinputVal = this.changeinputVal().bind(this);
}
getInitialState() {
return {
inputVal: ""
};
}
changeinputVal(e) {
this.setState({
inputVal: e.target.value
});
}
render() {
return (
<div className='task-container'>
<LeftComponent inputVal={this.state.inputVal} onChange={this.changeinputVal}/>
<RightComponent inputVal={this.state.inputVal} onChange={this.changeinputVal}/>
</div>
);

Categories