"Warning: Expected server HTML to contain a matching <img> in <a>." - How to use MagicZoom Plus in a server side app? -
How to use MagicZoom Plus in a server-side app like next js?
I see the following error when I refresh the page:
"Warning: Expected server HTML to contain a matching in ."
const [activeIndex, setActiveIndex] = useState(0);
<div>
<a href={item.src[activeIndex]} className="MagicZoom">
<img src={item.src[activeIndex]} alt="" />
</a>
</div>
See also questions close to this topic
-
Best practice for returning "nothing" from a ternary expression if falsy?
This is the ternary condition spec from mdn:
condition ? exprIfTrue : exprIfFalse
Often I find myself wanting to check if something is true, but I just want to do nothing with the falsy side of the expression. But I'm not sure how to write this:
(someVariable) ? callFunction(someVariable) : donothing but keep running the script
Should I use 'false', 'null', '', 'undefined' or something else?
The editor gives me an error if I just leave it open without anything to the right of the
:
-
Fetch API data with chain of .then methods, but data is not passing through to the next .then
I'm making three http get requests to create an array of unique objects. I'm sharing an example with a random API, not quite the same, but it's captures the essence: Codepen Example The main bug lies in the last 2 then methods of the getData function.
In the getData function, I pass the sorted list of users to the getUniqueGender function, where it fetches more data objects and pushes the first "unique" user by gender to the uniqueUsers array. The getUniqueGender function returns the uniqueUsers array but it doesn't seem to be doing that, why? I've added a console.log in line 28 (Codepen Example) to check if it's ready pushing the user into the array and it's doing so but it's returning an empty array to the next then method. In my actual code, the array passed to the next then method can be printed to the console but I cannot do any computation from that point on, it prints the array.length as 0 to the console.
Please help me debug this. I've been trying to debug this for days... :(
let uniqueUsers = []; let finalUsers = []; function sortUsers(arr) { /*dummy function to show the synchronous step*/ return arr; } function getUniqueGender(arr) { if (arr.length > 0) { for (let user of arr) { fetch('https://api.randomuser.me/?nat=US&results=${arr.length}') .then((res) => res.json()) .then((json) => json.results) .then((results) => { if (results.length > 0) { for (let res of results) { if (!uniqueUsers.some((uniqueUser) => uniqueUser.gender === res.gender)) { //console.log('users gender is unique so its added'); //console.log(res.gender); let editedUser = { gender: res.gender , email: res.email , }; uniqueUsers.push(editedUser); console.log(uniqueUsers) } else { //console.log('users gender is NOT unique so its NOT added'); //console.log(res.gender); } } } }); } //console.log(uniqueUsers) //this work in my actual code... return uniqueUsers; } else { return uniqueUsers; } } function appendInfo(arr) { console.log(arr) //this works in my actual code... for (let uniqueUser of arr) { fetch('https://api.randomuser.me/?nat=US&results=1') .then((res) => res.json()) .then((json) => json.results) .then((randomUser) => { let editedUniqueUser = { gender: uniqueUser.gender , email: uniqueUser.email , nat: randomUser.nat }; finalUsers.push(editedUniqueUser); }); } console.log(finalUsers) return finalUsers; } function getData() { fetch('https://api.randomuser.me/?nat=US&results=5') .then((res) => res.json()) .then((json) => json.results) .then((users) => sortUsers(users)) .then((sortedUsers) => getUniqueGender(sortedUsers)) .then((uniqueUsers) => appendInfo(uniqueUsers)) .then((result) => console.log(result)) //why this doesn't work?? .catch(console.log); } getData()
-
Calling multiple files from the same folder in a single file using module exports in Node
I'm trying to call multiple files from a single index.js file
Here is the current file structure
The index.js file:
const ApplicantRegister = require("./ApplicantRegister"); const ApplicantResidency = require("./ApplicantResidency"); const ApplicantPersonalDetails = require("./ApplicantPersonalDetails"); const ApplicantContactDetails = require("./ApplicantContactDetails"); const ApplicantEducation = require("./ApplicantEducation"); const models = { ApplicantRegister, ApplicantResidency, ApplicantPersonalDetails, ApplicantContactDetails, ApplicantEducation, }; module.exports = models;
Inside new.test.js
const { ApplicantRegister, ApplicantResidency, ApplicantPersonalDetails, ApplicantContactDetails, ApplicantEducation, } = require("../models");
The files in the models folder contain a single class (example):
class ApplicantRegister { constructor(page) { this.page = page; } async navigate() { await this.page.goto( "https://www.google.com" ); } }
Which I call in new.test.js:
test("Navigate to page", async () => { const register = new ApplicantRegister(page); await register.navigate(); });
I get the error: TypeError: ApplicantRegister is not a constructor
When I call the files individual (const ApplicantRegister = require("../models/ApplicantRegister") and add module.exports to the bottom of the individual files, it works.
Why does it give me the error when I try and require the files from a central file?
-
Display element over text - html,css,js
I want to overlap a ScrollMagic animation on a text, and not make the animation a separate section like it is right here:
There is supposed to be text over there but it made this animation into a new section where the text is at the bottom.
Code:
gsap.registerPlugin(MotionPathPlugin); const tween = gsap.timeline(); tween.to(".paper-plane", { duration: 1, ease: "power1.inOut", motionPath: { path: [ {x: 100, y: 0}, {x: 300, y: 10}, {x: 500, y: 100}, {x: 750, y: -100}, {x: 350, y: -50}, {x: 600, y: 100}, {x: 800, y: 0}, {x: window.innerWidth, y: -250} ], curviness: 2, autoRotate: true } }); const controller = new ScrollMagic.Controller(); const scene = new ScrollMagic.Scene({ triggerElement: '.animation', duration: 1000, triggerHook: 0 }) .setTween(tween) .setPin('.animation') .addTo(controller);
*{ margin: 0; padding: 0; box-sizing: border-box; } header, footer{ height: 100vh; display: flex; justify-content: center; align-items: center; font-family: "Montserrat", sans-serif; } header h1{ font-size: 60px; } .animation{ height: 100vh; position: relative; overflow: hidden; } .paper-plane{ position: absolute; top: 50%; left: 0%; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/ScrollMagic.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/plugins/animation.gsap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.2.6/MotionPathPlugin.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.6.0/gsap.min.js"></script> <div class="animation"> <img class="paper-plane" src="https://i.postimg.cc/W1w9dT1x/paper.png" alt="Paper Plane"> </div>
What would I need to add to my
css
so that the animation displays on top of the text, I have not provided the code for my text because it can be any text in general. I just want this animation to work over text and not have a separate section of its own. Any suggestions? -
Responsive website works on Desktop, Android phone but breaks on iphone even after using the media query and view port meta tags
Can someone help me understand why the site - https://amandeepsinghkhanna.github.io/about/ is responsive on the PC, on android phones but breaks on the iPhone. I have the media query as well as the viewport meta tag included in the code. It is hosted on GitHub-pages, if it helps in solving the issue.
-
How can I stop my html offset margins aggregating
I am adding buttons in an html form. There is an issue where the margin keeps growing by the width of the margin plus the width of the button on the previous row, as below:
I'm trying to make it so that all the buttons have an equal margin from the left.
My html looks like this:
<form class="my-form" id="atlas-info"> <div id="property-header">Atlas Settings</div> <hr /> <div class="form-group" id="tag-entry"> <label>Select tagging group: </label> <br /> <input type="text" name="name" id="tree"> </div> <div class="input-group">Dynamic key: </div> <button type="button" class="dynamic-key-button" id="filter-setting"></button> <label class="dynamic-key-text">Show if / show if not</label> <br /> @*below should not be hard coded, needs to be a loop of some sort*@ <button type="button" class="dynamic-key-button" id="organisation"></button> <label class="dynamic-key-text">Organisation</label> <br /> <button type="button" class="dynamic-key-button" id="job-executor"></button> <label class="dynamic-key-text">Job executor</label> <br /> <button type="button" class="dynamic-key-button" id="job-step"></button> <label class="dynamic-key-text">Job step</label> <br /> <button type="button" class="dynamic-key-button" id="product"></button> <label class="dynamic-key-text">Product</label> <br /> </form>
And my CSS as below:
.dynamic-key-button { height: 20px; width: 20px; border-radius: 10px; border: solid; cursor: pointer; padding-bottom: 12px; float: left; transition-duration: 0.4s; margin-left: 9px;
}
Any help would be appreciated.
-
Pass callback function from parent component to child component react
GOAL: Send callback function from parent to child to toggle sidebar component.
This code opens the sidebar:
<Sidebar show={status} /> <button onClick={() => setStatus((status) => !status)}> <SettingsIcon/> </button>
I use both true and false values for
status
to toggle the sidebar on and off.Now, in my sidebar component, I need to pass a
false
value toshow
so that is closes when myBack
button is clicked.const Sidebar = ({ show }) => { const { left } = useSpring({ from: { left: "-100%" }, left: show ? "0" : "-100%", }); return ( <animated.div style={{ left: left, position: "absolute", height: "100%", width: "55%", backgroundColor: "black", zIndex: 1, }} className="Sidebar" > <button onClick={() => !show}>Back</button> <p>hello</p> </animated.div> ); };
I can't seem to get it working. Any ideas what I am doing wrong?
-
React and Axios : Getting 'setIsLoaded' is not defined, 'setRowData' is not defined, 'RowData' is not defined
I am using React, node.js and this is my first time using Axios to connect to my Rest GET service (fetch all) on localhost:8080 which returns a list of saved users as a JSON array. However, I am unable to successfully connect and retrieve the data and got the following error:
Failed to compile src\App.js Line 16:7: 'setIsLoaded' is not defined no-undef Line 17:7: 'setRowData' is not defined no-undef Line 35:13: 'rowData' is not defined no-undef
I suspect perhaps I haven't imported some components properly?
Here is my code :
import React, { useEffect } from "react"; import { axios } from 'axios'; import { jsonServerRestClient, Admin, Resource, Delete } from 'admin-on-rest'; import { DataGrid } from '@material-ui/data-grid'; export default function App() { useEffect(() => { const apiurl = "http://localhost:8080/user/all"; axios .get(apiurl) .then((response) => response.data) .then((data) => { setIsLoaded(true); setRowData(data); }); }, []); const columns = [ { field: "id", headerName: "ID", width: 10 }, { field: "userName", headerName: "Name", width: 170 }, { field: "userTelNo", headerName: "Tel No", width: 70 }, { field: "userEmail", headerName: "EMail", width: 100 }, { field: "userRole", headerName: "Role", width: 100 }, ]; return( <DataGrid rows={rowData} columns={columns} id="id" pageSize={15} checkboxSelection /> ); }
I confirmed that upon checking the GET URL on my browser address bar (http://localhost:8080/user/all), the JSON is returning properly (as an array of JSONs) as shown below:
[{"id":1,"userName":"admin","userPassword":"admin123","userTelNo":"012-104-1001","userEmail":"admin@fsgsm.com","userRole":"管理员","loginDateTime":"2021-01-25T09:57:38","entryDateTime":"2021-01-25T09:57:31","updateDateTime":"2021-01-25T09:57:40"}, {"id":2,"userName":"t","userPassword":"admin123","userTelNo":"","userEmail":"","userRole":"开发 人员","loginDateTime":"2021-01-25T11:15:53","entryDateTime":"2021-01-25T11:15:53","updateDateTime":"2021-01-25T11:15:53"}, {"id":3,"userName":"324","userPassword":"43444","userTelNo":"4334","userEmail":"344","userRole":"开发 人员","loginDateTime":"2021-01-25T23:12:38","entryDateTime":"2021-01-25T23:12:38","updateDateTime":"2021-01-25T23:12:38"}]
One other thing: For the API URL, am I supplying the URL string correctly with the current "http://localhost:8080/user/all" or should it be "localhost:8080/user/all" or just "/user/all" ? Thank you in advance!
-
how to set default value in case of error
I'm learning React and I'm trying to render 10 pieces of data from a specific API. This is a function I wrote for iterating through the fetched data and taking the title and the image:
for (let i = 0; i < 10; i++) { data.push({ title: someMethod(allData)[i].children[0].data, image: someMethod(allData)[i].attribs.src, }); }
I don't know why but one of the images gives me that error:
index.js:1 TypeError: Cannot read property 'attribs' of undefined
Which stops the whole rendering. I wanted to try to put a temporary placeholder image so the rest of the images can be loaded without any errors.
I thought about adding conditions into the image line inside the loop but it didn't work for me. What's the right way to do that?
If I wasn't clear enough please comment what wasn't clear and I'll try to describe it better.
-
How to fix the Request failed with status code 500 when reload page in react
The problem here is when every time I reload the page I'm getting this error. which is the
Uncaught (in promise) Error: Request failed with status code 500
.here's my code in list.tsx
const [state, setState] = useState([]); const { getRoom } = useRoom(); const fetchData = async () => { return getRoom().then((res) => setState(res['data'].data)); } useEffect(() => { (async function fetchData() { await fetchData(); })(); })
code for room.tsx
function useRoom() { const creds = useCredentials(); Axios.defaults.baseURL = serverConfig[creds.server].api; return { getRoom: (params?: object) => Axios.get(`${API_URL}/room` + (params ? getQueryParams(params) : '')) }; }
-
How to fetch a data without using useffect or setTimeout and add loader in react hooks
DETAIL*
const Detail = (props) { const { getLatest, getAll } = useRoom(); const [ rowData, setRowData ] = useState([]); const [ state, setState ] = useState([]); useEffect(() => { const fetchData = async () => { getLatest(PARAMS).then((res) => setState(res['data'].data)); getAll({length: 9999}).then((res) => setRowData(res['data'].data)); } fetchData(); }, []); return ( {state && state.map((res, i) => ( <div key={i} className="w-full px-2 flex rounded justify-center items-center p-2 m-1 bg-white"> <Room item={res} /> </div> ))} ) } export default Detail;
What I'm trying to do here is to add a loader also my problem is when I didn't use the setTimeout I'm getting error which is
Request failed with status code 500
. but when I added the setTimeout there's no error.setTimeout(() => {...fetchData }
API CALLING
getLatest: (params?: object) => Axios.get(`${API_URL}/latest` + (params ? getQueryParams(params) : ''))
-
Too many requests, please try again later. Next JS no backend
I need help to solve this issue. I'm new at next js ... and every time I refresh my page i get the error "Too many requests, please try again later". This also happens if I click the button too many times. Any one has any Idea how to solve this. Thanks that will be a great help.
using the boiler plate: @pankod/next-boilerplate.
function believe(): void { router.push('/user/believe'); } <button type="submit" className="btn btn--believe color-white w-100 font-14" onClick={believe}> Believe </button>
P.S I'm just a newbie
-
MagicZoomPlus why when zoom in is showing the first image?
Currently, I have this issue that if I want to zoom in the second or third image I see the first image, I don’t know why is this happening? Could you please run this project and help me to understand what’s going on?
Here is my repo,
- npm install
- npm start
-
How to run Magic Zoom Plus in a next js app?
How can I run Magic Zoom in a next js app?I put the magiczoomplus folder in the static folder of next js then put these lines
<link type="text/css" rel="stylesheet" href="magiczoomplus/magiczoomplus.css" /> <script type="text/javascript" src="magiczoomplus/magiczoomplus.js" ></script>
in the _document.js file. Then I tried to use useffect. What am I doing wrong?
Unhandled Runtime Error ReferenceError: MagicZoom is not defined
useEffect(() => { if (MagicZoom !== undefined) { $mjs(document).jAddEvent("domready", function () { MagicZoom.start(); }); setMounted(true); } }, []);