Error: Cannot create styled-component for component: undefined - reactjs

j
X:/rstfrontend/packages/src/constants.js:4
1 | // #flow
2 |
3 | declare var SC_DISABLE_SPEEDY: ?boolean;
> 4 | declare var __VERSION__: string;
5 |
6 | export const SC_ATTR: string =
7 | (typeof process !== 'undefined' && (process.env.REACT_APP_SC_ATTR || process.env.SC_ATTR)) ||
Another problem is that it refers to a path that doesn't exist.
When clicked on View Compiled it links to main.chunk.
Maybe a bug with webpack?
j
http://localhost:3000/static/js/vendors~main.chunk.js:187248:30
187245 | n[r - 1] = arguments[r];
187246 | }
187247 |
> 187248 | throw false ? undefined : new Error(D.apply(void 0, [R[e]].concat(n)).trim());
| ^ 187249 | }
187250 |
187251 | var T = function () {

Related

TypeError: render is not a function while using React Context along with React Router

I need to set up a user state that can be called from different components. This setup uses React Router and React Context.
The React context contains just a single state that keeps track of the user's name.
At the top-level i.e App I have passed all the children on to the provider. But I get an error
TypeError: render is not a function
My UserContext code:
const UserContext = createContext();
export const UserProvider = (props) => {
const [user, setUser] = useState("");
return (
<UserContext.Provider value={[user, setUser]}>
{props.children}
</UserContext.Provider>
);
};
export default UserContext;
My App code :
function App() {
return (
<UserProvider>
<Router>
<div>
<Nav />
<Switch>
<Route exact path="/" component={Signup} />
<Route exact path="/signin" component={SignIn} />
<Route path="/register" component={UserRegister} />
<Route path="/homepage/:user" component={Homepage} />
</Switch>
</div>
</Router>
</UserProvider>
);
}
export default App;
The entrie error log:
TypeError: render is not a function
updateContextConsumer
G:/WebDevelopmentFolder/trinkerrchallenge/node_modules/react-dom/cjs/react-dom.development.js:18747
18744 | {
18745 | ReactCurrentOwner$1.current = workInProgress;
18746 | setIsRendering(true);
> 18747 | newChildren = render(newValue);
| ^ 18748 | setIsRendering(false);
18749 | } // React DevTools reads this flag.
18750 |
View compiled
beginWork
G:/WebDevelopmentFolder/trinkerrchallenge/node_modules/react-dom/cjs/react-dom.development.js:19114
19111 | return updateContextProvider(current, workInProgress, renderLanes);
19112 |
19113 | case ContextConsumer:
> 19114 | return updateContextConsumer(current, workInProgress, renderLanes);
| ^ 19115 |
19116 | case MemoComponent:
19117 | {
View compiled
HTMLUnknownElement.callCallback
G:/WebDevelopmentFolder/trinkerrchallenge/node_modules/react-dom/cjs/react-dom.development.js:3945
3942 | function callCallback() {
3943 | didCall = true;
3944 | restoreAfterDispatch();
> 3945 | func.apply(context, funcArgs);
| ^ 3946 | didError = false;
3947 | } // Create a global error event handler. We use this to capture the value
3948 | // that was thrown. It's possible that this error handler will fire more
View compiled
invokeGuardedCallbackDev
G:/WebDevelopmentFolder/trinkerrchallenge/node_modules/react-dom/cjs/react-dom.development.js:3994
3991 | // errors, it will trigger our global error handler.
3992 |
3993 | evt.initEvent(evtType, false, false);
> 3994 | fakeNode.dispatchEvent(evt);
| ^ 3995 |
3996 | if (windowEventDescriptor) {
3997 | Object.defineProperty(window, 'event', windowEventDescriptor);
View compiled
invokeGuardedCallback
G:/WebDevelopmentFolder/trinkerrchallenge/node_modules/react-dom/cjs/react-dom.development.js:4056
4053 | function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
4054 | hasError = false;
4055 | caughtError = null;
> 4056 | invokeGuardedCallbackImpl$1.apply(reporter, arguments);
4057 | }
4058 | /**
4059 | * Same as invokeGuardedCallback, but instead of returning an error, it stores
View compiled
beginWork$1
G:/WebDevelopmentFolder/trinkerrchallenge/node_modules/react-dom/cjs/react-dom.development.js:23964
23961 | } // Run beginWork again.
23962 |
23963 |
> 23964 | invokeGuardedCallback(null, beginWork, null, current, unitOfWork, lanes);
| ^ 23965 |
23966 | if (hasCaughtError()) {
23967 | var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.
View compiled
performUnitOfWork
G:/WebDevelopmentFolder/trinkerrchallenge/node_modules/react-dom/cjs/react-dom.development.js:22776
22773 |
22774 | if ( (unitOfWork.mode & ProfileMode) !== NoMode) {
22775 | startProfilerTimer(unitOfWork);
> 22776 | next = beginWork$1(current, unitOfWork, subtreeRenderLanes);
| ^ 22777 | stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
22778 | } else {
22779 | next = beginWork$1(current, unitOfWork, subtreeRenderLanes);
View compiled
workLoopSync
G:/WebDevelopmentFolder/trinkerrchallenge/node_modules/react-dom/cjs/react-dom.development.js:22707
22704 | function workLoopSync() {
22705 | // Already timed out, so perform work without checking if we need to yield.
22706 | while (workInProgress !== null) {
> 22707 | performUnitOfWork(workInProgress);
22708 | }
22709 | }
22710 |
View compiled
renderRootSync
G:/WebDevelopmentFolder/trinkerrchallenge/node_modules/react-dom/cjs/react-dom.development.js:22670
22667 |
22668 | do {
22669 | try {
> 22670 | workLoopSync();
| ^ 22671 | break;
22672 | } catch (thrownValue) {
22673 | handleError(root, thrownValue);
View compiled
performSyncWorkOnRoot
G:/WebDevelopmentFolder/trinkerrchallenge/node_modules/react-dom/cjs/react-dom.development.js:22293
22290 | }
22291 | } else {
22292 | lanes = getNextLanes(root, NoLanes);
> 22293 | exitStatus = renderRootSync(root, lanes);
| ^ 22294 | }
22295 |
22296 | if (root.tag !== LegacyRoot && exitStatus === RootErrored) {
View compiled
scheduleUpdateOnFiber
G:/WebDevelopmentFolder/trinkerrchallenge/node_modules/react-dom/cjs/react-dom.development.js:21881
21878 | // root inside of batchedUpdates should be synchronous, but layout updates
21879 | // should be deferred until the end of the batch.
21880 |
> 21881 | performSyncWorkOnRoot(root);
| ^ 21882 | } else {
21883 | ensureRootIsScheduled(root, eventTime);
21884 | schedulePendingInteractions(root, lane);
View compiled
updateContainer
G:/WebDevelopmentFolder/trinkerrchallenge/node_modules/react-dom/cjs/react-dom.development.js:25482
25479 | }
25480 |
25481 | enqueueUpdate(current$1, update);
> 25482 | scheduleUpdateOnFiber(current$1, lane, eventTime);
25483 | return lane;
25484 | }
25485 | function getPublicRootInstance(container) {
View compiled
(anonymous function)
G:/WebDevelopmentFolder/trinkerrchallenge/node_modules/react-dom/cjs/react-dom.development.js:26021
26018 |
26019 |
26020 | unbatchedUpdates(function () {
> 26021 | updateContainer(children, fiberRoot, parentComponent, callback);
| ^ 26022 | });
26023 | } else {
26024 | fiberRoot = root._internalRoot;
View compiled
unbatchedUpdates
G:/WebDevelopmentFolder/trinkerrchallenge/node_modules/react-dom/cjs/react-dom.development.js:22431
22428 | executionContext |= LegacyUnbatchedContext;
22429 |
22430 | try {
> 22431 | return fn(a);
| ^ 22432 | } finally {
22433 | executionContext = prevExecutionContext;
22434 |
View compiled
legacyRenderSubtreeIntoContainer
G:/WebDevelopmentFolder/trinkerrchallenge/node_modules/react-dom/cjs/react-dom.development.js:26020
26017 | } // Initial mount should not be batched.
26018 |
26019 |
> 26020 | unbatchedUpdates(function () {
| ^ 26021 | updateContainer(children, fiberRoot, parentComponent, callback);
26022 | });
26023 | } else {
View compiled
render
G:/WebDevelopmentFolder/trinkerrchallenge/node_modules/react-dom/cjs/react-dom.development.js:26103
26100 | }
26101 | }
26102 |
> 26103 | return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
26104 | }
26105 | function unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
26106 | if (!isValidContainer(containerNode)) {
View compiled
Module.<anonymous>
G:/WebDevelopmentFolder/trinkerrchallenge/src/index.js:6
3 | import "./index.css";
4 | import App from "./App";
5 |
> 6 | ReactDOM.render(
7 | <React.StrictMode>
8 | <App />
9 | </React.StrictMode>,
View compiled
Module../src/index.js
http://localhost:3000/static/js/main.chunk.js:1581:30
__webpack_require__
G:/WebDevelopmentFolder/trinkerrchallenge/webpack/bootstrap:851
848 |
849 | __webpack_require__.$Refresh$.init();
850 | try {
> 851 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
| ^ 852 | } finally {
853 | __webpack_require__.$Refresh$.cleanup(moduleId);
854 | }
View compiled
fn
G:/WebDevelopmentFolder/trinkerrchallenge/webpack/bootstrap:150
147 | );
148 | hotCurrentParents = [];
149 | }
> 150 | return __webpack_require__(request);
| ^ 151 | };
152 | var ObjectFactory = function ObjectFactory(name) {
153 | return {
View compiled
1
http://localhost:3000/static/js/main.chunk.js:1595:18
__webpack_require__
G:/WebDevelopmentFolder/trinkerrchallenge/webpack/bootstrap:851
848 |
849 | __webpack_require__.$Refresh$.init();
850 | try {
> 851 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
| ^ 852 | } finally {
853 | __webpack_require__.$Refresh$.cleanup(moduleId);
854 | }
View compiled
checkDeferredModules
G:/WebDevelopmentFolder/trinkerrchallenge/webpack/bootstrap:45
42 | }
43 | if(fulfilled) {
44 | deferredModules.splice(i--, 1);
> 45 | result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
| ^ 46 | }
47 | }
48 |
View compiled
Array.webpackJsonpCallback [as push]
G:/WebDevelopmentFolder/trinkerrchallenge/webpack/bootstrap:32
29 | deferredModules.push.apply(deferredModules, executeModules || []);
30 |
31 | // run deferred modules when all chunks ready
> 32 | return checkDeferredModules();
| ^ 33 | };
34 | function checkDeferredModules() {
35 | var result;

What are the best alternatives for javascript clientWidth in reactjs?

I am trying to convert JavaScript code to ReactJS.
The compiler doesn't display any error but browser is throwing an error at runtime.
I expect to see it workable but I am getting some errors.
My slider is not displaying the images even when I click on left or right arrows then browser takes me for debugging when i comment these two lines
const size = carouselImages[0].clientWidth;
carouselSlide.style.transform = 'translateX(' + (size * counter) + 'px)'
-----------------------------------Carousel.css--------------------------
* {
padding:0px;
margin:0px;
box-sizing:border-box;
}
.carousel-container
{
width:60%;
margin:auto;
border: 5px solid black;
overflow:hidden;
position: relative;
}
.carousel-slide{
display: flex;
width:100%;
height:500px;
}
#prevBtn{
position:absolute;
top: 50%;
z-index:10;
left:5%;
font-size:30px;
color:grey;
opacity: 0.9;
cursor:pointer;
}
#nextBtn{
position:absolute;
top: 50%;
z-index:10;
right:5%;
font-size:30px;
color:grey;
opacity: 0.9;
cursor:pointer;
}
-----------------------------------Carousel.js--------------------------
import React from "react";
import './Carousel.css'
const Carousel = () => {
const carouselSlide = document.querySelector('.carousel-slide');
const carouselImages = document.querySelectorAll('.carousel-slide img');
let counter = 1;
const size = carouselImages[0].clientWidth;
carouselSlide.style.transform = 'translateX(' + (size * counter) + 'px)'
function showNextItemFlex() {
debugger;
if(counter >= carouselImages.length - 1) return;
carouselSlide.style.transition = "transform 0.4s ease-in-out";
counter ++;
// console.log(counter);
carouselSlide.style.transform = 'translateX('+ (size * counter) + 'px)';
}
function showPreviousItemFlex() {
debugger;
if(counter <= 0) return;
carouselSlide.style.transition = "transform 0.4s ease-in-out";
counter--;
// console.log(counter);
carouselSlide.style.transform = 'translateX('+ (size * counter) + 'px)';
}
function fireTransitioned()
{
debugger;
if(carouselImages[counter].id === 'lastClone')
{
carouselSlide.style.transition = "none";
counter = carouselImages.length - 2;
carouselSlide.style.transform = 'translateX('+ (size * counter) + 'px)';
}
if(carouselImages[counter].id === 'firstClone')
{
carouselSlide.style.transition = "none";
counter = carouselImages.length - counter;
carouselSlide.style.transform = 'translateX('+ (size * counter) + 'px)';
}
}
return (
<div className="carousel-container">
{/* <i id="prevBtn" onClick={showPreviousItem}>❮</i>
<i id="nextBtn" onClick={showNextItem}>❯</i> */}
<i id="prevBtn" onClick={showPreviousItemFlex}>❮</i>
<i id="nextBtn" onClick={showNextItemFlex}>❯</i>
<div className="carousel-slide" onTransitionEnd={fireTransitioned}>
<img id="lastClone" src="https://source.unsplash.com/InR-EhiO_js" alt="None"/>
<img src="https://source.unsplash.com/gKk9rpyDryU" alt="None " />
<img src="https://source.unsplash.com/VFGEhLznjPU" alt="None"/>
<img src="https://source.unsplash.com/InR-EhiO_js" alt="None"/>
<img id="firstClone" src="https://source.unsplash.com/gKk9rpyDryU" alt="None " />
</div>
</div>
);
}
export default Carousel;
Application built with
{
"react": "16.13.0",
"react-dom": "^16.13.0",
"react-redux": "^7.2.0",
"redux": "^4.0.4"
"#material-ui/core": "^4.9.5"
}
Now see the errors below:
TypeError: Cannot read property 'clientWidth' of undefined
CarouselFlex
H:/ReactJs/Source Codes/react-master/react-master/src/components/Sliders/Carousel.js:9
6 | const carouselSlide = document.querySelector('.carousel-slide');
7 | const carouselImages = document.querySelectorAll('.carousel-slide img');
8 | let counter = 1;
> 9 | const size = carouselImages[0].clientWidth;
10 | carouselSlide.style.transform = 'translateX(' + (size * counter) + 'px)'
11 |
12 | // // Similar to componentDidMount and componentDidUpdate:
View compiled
renderWithHooks
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:14803
14800 | }
14801 | }
14802 |
> 14803 | var children = Component(props, secondArg); // Check if there was a render phase update
| ^ 14804 |
14805 | if (workInProgress.expirationTime === renderExpirationTime) {
14806 | // Keep rendering in a loop for as long as render phase updates continue to
View compiled
mountIndeterminateComponent
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:17482
17479 |
17480 | setIsRendering(true);
17481 | ReactCurrentOwner$1.current = workInProgress;
> 17482 | value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
| ^ 17483 | setIsRendering(false);
17484 | } // React DevTools reads this flag.
17485 |
View compiled
beginWork
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:18596
18593 | switch (workInProgress.tag) {
18594 | case IndeterminateComponent:
18595 | {
> 18596 | return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderExpirationTime);
| ^ 18597 | }
18598 |
18599 | case LazyComponent:
View compiled
HTMLUnknownElement.callCallback
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:188
185 | window.event = windowEvent;
186 | }
187 |
> 188 | func.apply(context, funcArgs);
| ^ 189 | didError = false;
190 | } // Create a global error event handler. We use this to capture the value
191 | // that was thrown. It's possible that this error handler will fire more
View compiled
invokeGuardedCallbackDev
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:237
234 | // errors, it will trigger our global error handler.
235 |
236 | evt.initEvent(evtType, false, false);
> 237 | fakeNode.dispatchEvent(evt);
| ^ 238 |
239 | if (windowEventDescriptor) {
240 | Object.defineProperty(window, 'event', windowEventDescriptor);
View compiled
invokeGuardedCallback
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:292
289 | function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
290 | hasError = false;
291 | caughtError = null;
> 292 | invokeGuardedCallbackImpl$1.apply(reporter, arguments);
293 | }
294 | /**
295 | * Same as invokeGuardedCallback, but instead of returning an error, it stores
View compiled
beginWork$1
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:23203
23200 | } // Run beginWork again.
23201 |
23202 |
> 23203 | invokeGuardedCallback(null, beginWork, null, current, unitOfWork, expirationTime);
| ^ 23204 |
23205 | if (hasCaughtError()) {
23206 | var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.
View compiled
performUnitOfWork
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:22154
22151 |
22152 | if ( (unitOfWork.mode & ProfileMode) !== NoMode) {
22153 | startProfilerTimer(unitOfWork);
> 22154 | next = beginWork$1(current, unitOfWork, renderExpirationTime$1);
| ^ 22155 | stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
22156 | } else {
22157 | next = beginWork$1(current, unitOfWork, renderExpirationTime$1);
View compiled
workLoopSync
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:22130
22127 | function workLoopSync() {
22128 | // Already timed out, so perform work without checking if we need to yield.
22129 | while (workInProgress !== null) {
> 22130 | workInProgress = performUnitOfWork(workInProgress);
22131 | }
22132 | }
22133 | /** #noinline */
View compiled
performSyncWorkOnRoot
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:21756
21753 |
21754 | do {
21755 | try {
> 21756 | workLoopSync();
| ^ 21757 | break;
21758 | } catch (thrownValue) {
21759 | handleError(root, thrownValue);
View compiled
scheduleUpdateOnFiber
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:21188
21185 | // root inside of batchedUpdates should be synchronous, but layout updates
21186 | // should be deferred until the end of the batch.
21187 |
> 21188 | performSyncWorkOnRoot(root);
| ^ 21189 | } else {
21190 | ensureRootIsScheduled(root);
21191 | schedulePendingInteractions(root, expirationTime);
View compiled
updateContainer
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:24373
24370 | }
24371 |
24372 | enqueueUpdate(current$1, update);
> 24373 | scheduleWork(current$1, expirationTime);
24374 | return expirationTime;
24375 | }
24376 | function getPublicRootInstance(container) {
View compiled
(anonymous function)
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:24758
24755 |
24756 |
24757 | unbatchedUpdates(function () {
> 24758 | updateContainer(children, fiberRoot, parentComponent, callback);
| ^ 24759 | });
24760 | } else {
24761 | fiberRoot = root._internalRoot;
View compiled
unbatchedUpdates
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:21903
21900 | executionContext |= LegacyUnbatchedContext;
21901 |
21902 | try {
> 21903 | return fn(a);
| ^ 21904 | } finally {
21905 | executionContext = prevExecutionContext;
21906 |
View compiled
legacyRenderSubtreeIntoContainer
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:24757
24754 | } // Initial mount should not be batched.
24755 |
24756 |
> 24757 | unbatchedUpdates(function () {
| ^ 24758 | updateContainer(children, fiberRoot, parentComponent, callback);
24759 | });
24760 | } else {
View compiled
render
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:24840
24837 | }
24838 | }
24839 |
> 24840 | return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
24841 | }
24842 | function unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
24843 | if (!isValidContainer(containerNode)) {
View compiled
Module../src/index.js
H:/ReactJs/Source Codes/react-master/react-master/src/index.js:9
6 | import reducer, { initialState } from "./reducer";
7 | import { StateProvider } from "./StateProvider";
8 |
> 9 | ReactDOM.render(
10 | <React.StrictMode>
11 | <StateProvider initialState={initialState} reducer={reducer}>
12 | <App />
View compiled
__webpack_require__
H:/ReactJs/Source Codes/react-master/react-master/webpack/bootstrap:784
781 | };
782 |
783 | // Execute the module function
> 784 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
| ^ 785 |
786 | // Flag the module as loaded
787 | module.l = true;
View compiled
fn
H:/ReactJs/Source Codes/react-master/react-master/webpack/bootstrap:150
147 | );
148 | hotCurrentParents = [];
149 | }
> 150 | return __webpack_require__(request);
| ^ 151 | };
152 | var ObjectFactory = function ObjectFactory(name) {
153 | return {
View compiled
1
http://localhost:3000/static/js/main.chunk.js:3421:18
__webpack_require__
H:/ReactJs/Source Codes/react-master/react-master/webpack/bootstrap:784
781 | };
782 |
783 | // Execute the module function
> 784 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
| ^ 785 |
786 | // Flag the module as loaded
787 | module.l = true;
View compiled
checkDeferredModules
H:/ReactJs/Source Codes/react-master/react-master/webpack/bootstrap:45
42 | }
43 | if(fulfilled) {
44 | deferredModules.splice(i--, 1);
> 45 | result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
| ^ 46 | }
47 | }
48 |
View compiled
Array.webpackJsonpCallback [as push]
H:/ReactJs/Source Codes/react-master/react-master/webpack/bootstrap:32
29 | deferredModules.push.apply(deferredModules, executeModules || []);
30 |
31 | // run deferred modules when all chunks ready
> 32 | return checkDeferredModules();
| ^ 33 | };
34 | function checkDeferredModules() {
35 | var result;
View compiled
(anonymous function)
I changed your code to React style It works now, but it has some bugs yet:
when your click in transition time
when you change direction.
It's good point to start your work.
.carousel-slide{
display: flex;
width:100%; // - also I removed it
height:500px;
}
component:
import React, { useState, useRef, useEffect } from "react";
import "./Carousel.css";
const Carousel = () => {
const [counter, setCounter] = useState(0);
const [isNextClick, setIsNextClick] = useState(false);
const [size, setSize] = useState(1);
const [carouselImages, setCarouselImages] = useState(null);
const carouselSlideRef = useRef();
useEffect(() => {
const images = document.querySelectorAll("img");
const size_ = images[0].clientWidth;
setCarouselImages(images);
setSize(size_);
}, [counter, size]);
function showNextItemFlex() {
carouselSlideRef.current.style.transition = "transform 0.4s ease-in-out";
const counter_ = counter < carouselImages.length - 1 ? counter + 1 : 0;
setCounter(counter_);
setIsNextClick(true);
carouselSlideRef.current.style.transform = `translateX(${
-size * counter_
}px)`;
}
function showPreviousItemFlex() {
carouselSlideRef.current.style.transition = "transform 0.4s ease-in-out";
const counter_ = counter <= 0 ? carouselImages.length - 1 : counter - 1;
setCounter(counter_);
setIsNextClick(false);
carouselSlideRef.current.style.transform = `translateX(${
-size * counter_
}px)`;
}
function fireTransitioned() {
if (carouselImages[counter].id === "lastClone" && !isNextClick) {
carouselSlideRef.current.style.transition = "none";
const counter_ = carouselImages.length - 1;
setCounter(counter_);
carouselSlideRef.current.style.transform =
"translateX(" + -size * counter_ + "px)";
}
if (carouselImages[counter].id === "firstClone" && isNextClick) {
carouselSlideRef.current.style.transition = "none";
const counter_ = 0;
setCounter(counter_);
carouselSlideRef.current.style.transform =
"translateX(" + -size * counter_ + "px)";
}
}
return (
<>
<p>{counter}</p>
<div className="carousel-container">
{/* <i id="prevBtn" onClick={showPreviousItem}>❮</i>
<i id="nextBtn" onClick={showNextItem}>❯</i> */}
<i id="prevBtn" onClick={showPreviousItemFlex}>
❮
</i>
<i id="nextBtn" onClick={showNextItemFlex}>
❯
</i>
<div
ref={carouselSlideRef}
className="carousel-slide"
onTransitionEnd={fireTransitioned}
>
<img
id="lastClone"
src="https://source.unsplash.com/InR-EhiO_js"
alt="None"
/>
<img src="https://source.unsplash.com/gKk9rpyDryU" alt="None " />
<img src="https://source.unsplash.com/VFGEhLznjPU" alt="None" />
<img
id="firstClone"
src="https://source.unsplash.com/InR-EhiO_js"
alt="None"
/>
</div>
</div>
</>
);
};
export default Carousel;

How to convert Image Slider Javascript code to reactjs using Hooks

I am trying to convert the JavaScript sample code in ReactJS.
The compiler doesn't display any error but browser is throwing an error at runtime.
I am using this example, please see below.
https://codepen.io/kathykato/pen/prEmKe
I expect to see it workable as displays in above example but I am getting small errors.
What I have tried so far is given below
-------------------------Carousel.js--------------------------
import React, { useState, useEffect } from "react";
import './Carousel.scss'
const Carousel = () => {
const items = document.querySelectorAll('img');
const itemCount = items.length;
const nextItem = document.querySelector('.next');
const previousItem = document.querySelector('.previous');
let count = 0;
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
nextItem.addEventListener('click', showNextItem);
previousItem.addEventListener('click', showPreviousItem);
document.addEventListener('keydown', keyPress);
// clean up
return () => {
nextItem.removeEventListener('click', showNextItem);
previousItem.removeEventListener('click', showPreviousItem);
document.removeEventListener('keydown', keyPress);
};
})
function showNextItem() {
items[count].classList.remove('active');
if(count < itemCount - 1) {
count++;
} else {
count = 0;
}
items[count].classList.add('active');
console.log(count);
}
function showPreviousItem() {
items[count].classList.remove('active');
if(count > 0) {
count--;
} else {
count = itemCount - 1;
}
items[count].classList.add('active');
console.log(count);
}
function keyPress(e) {
e = e || window.event;
if (e.keyCode == '37') {
showPreviousItem();
} else if (e.keyCode == '39') {
showNextItem();
}
}
// nextItem.addEventListener('click', showNextItem);
// previousItem.addEventListener('click', showPreviousItem);
// document.addEventListener('keydown', keyPress);
return (
<div className="container">
<div className="slider">
<img className="active" src="https://source.unsplash.com/gKk9rpyDryU" alt="Nothing " />
<img src="https://source.unsplash.com/VFGEhLznjPU" alt="Nothing"/>
<img src="https://source.unsplash.com/InR-EhiO_js" alt="Nothing"/>
</div>
<nav className="slider-nav">
<ul>
<li className="arrow">
<button className="previous">
<span>
<i className="ion-arrow-left-c"></i>
</span>
</button>
</li>
<li className="arrow">
<button className="next">
<span>
<i className="ion-arrow-right-c"></i>
</span>
</button>
</li>
</ul>
</nav>
</div>
);
}
export default Carousel;
Application built with
{
"react": "16.13.0",
"react-dom": "^16.13.0",
"react-redux": "^7.2.0",
"redux": "^4.0.4"
"#material-ui/core": "^4.9.5"
}
Now see the errors below:
TypeError: Cannot read property 'addEventListener' of null
(anonymous function)
H:/ReactJs/Source Codes/react-master/react-master/src/components/Sliders/Carousel.js:14
11 |
12 | // Similar to componentDidMount and componentDidUpdate:
13 | useEffect(() => {
> 14 | nextItem.addEventListener('click', showNextItem);
| ^ 15 | previousItem.addEventListener('click', showPreviousItem);
16 | document.addEventListener('keydown', keyPress);
17 |
View compiled
commitHookEffectListMount
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:19731
19728 | if ((effect.tag & tag) === tag) {
19729 | // Mount
19730 | var create = effect.create;
> 19731 | effect.destroy = create();
| ^ 19732 |
19733 | {
19734 | var destroy = effect.destroy;
View compiled
commitPassiveHookEffects
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:19769
19766 | // before calling any create functions. The current approach only serializes
19767 | // these for a single fiber.
19768 | commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork);
> 19769 | commitHookEffectListMount(Passive$1 | HasEffect, finishedWork);
| ^ 19770 | break;
19771 | }
19772 | }
View compiled
HTMLUnknownElement.callCallback
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:188
185 | window.event = windowEvent;
186 | }
187 |
> 188 | func.apply(context, funcArgs);
| ^ 189 | didError = false;
190 | } // Create a global error event handler. We use this to capture the value
191 | // that was thrown. It's possible that this error handler will fire more
View compiled
invokeGuardedCallbackDev
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:237
234 | // errors, it will trigger our global error handler.
235 |
236 | evt.initEvent(evtType, false, false);
> 237 | fakeNode.dispatchEvent(evt);
| ^ 238 |
239 | if (windowEventDescriptor) {
240 | Object.defineProperty(window, 'event', windowEventDescriptor);
View compiled
invokeGuardedCallback
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:292
289 | function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
290 | hasError = false;
291 | caughtError = null;
> 292 | invokeGuardedCallbackImpl$1.apply(reporter, arguments);
293 | }
294 | /**
295 | * Same as invokeGuardedCallback, but instead of returning an error, it stores
View compiled
flushPassiveEffectsImpl
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:22853
22850 | while (_effect2 !== null) {
22851 | {
22852 | setCurrentFiber(_effect2);
> 22853 | invokeGuardedCallback(null, commitPassiveHookEffects, null, _effect2);
| ^ 22854 |
22855 | if (hasCaughtError()) {
22856 | if (!(_effect2 !== null)) {
View compiled
unstable_runWithPriority
H:/ReactJs/Source Codes/react-master/react-master/node_modules/scheduler/cjs/scheduler.development.js:653
650 | currentPriorityLevel = priorityLevel;
651 |
652 | try {
> 653 | return eventHandler();
| ^ 654 | } finally {
655 | currentPriorityLevel = previousPriorityLevel;
656 | }
View compiled
runWithPriority$1
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:11039
11036 |
11037 | function runWithPriority$1(reactPriorityLevel, fn) {
11038 | var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
> 11039 | return Scheduler_runWithPriority(priorityLevel, fn);
11040 | }
11041 | function scheduleCallback(reactPriorityLevel, callback, options) {
11042 | var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
View compiled
flushPassiveEffects
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:22820
22817 | if (pendingPassiveEffectsRenderPriority !== NoPriority) {
22818 | var priorityLevel = pendingPassiveEffectsRenderPriority > NormalPriority ? NormalPriority : pendingPassiveEffectsRenderPriority;
22819 | pendingPassiveEffectsRenderPriority = NoPriority;
> 22820 | return runWithPriority$1(priorityLevel, flushPassiveEffectsImpl);
22821 | }
22822 | }
22823 |
View compiled
(anonymous function)
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:22699
22696 | if (!rootDoesHavePassiveEffects) {
22697 | rootDoesHavePassiveEffects = true;
22698 | scheduleCallback(NormalPriority, function () {
> 22699 | flushPassiveEffects();
| ^ 22700 | return null;
22701 | });
22702 | }
View compiled
workLoop
H:/ReactJs/Source Codes/react-master/node_modules/scheduler/cjs/scheduler.development.js:597
594 | currentPriorityLevel = currentTask.priorityLevel;
595 | var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
596 | markTaskRun(currentTask, currentTime);
> 597 | var continuationCallback = callback(didUserCallbackTimeout);
| ^ 598 | currentTime = exports.unstable_now();
599 |
600 | if (typeof continuationCallback === 'function') {
View compiled
flushWork
H:/ReactJs/Source Codes/react-master/node_modules/scheduler/cjs/scheduler.development.js:552
549 | try {
550 | if (enableProfiling) {
551 | try {
> 552 | return workLoop(hasTimeRemaining, initialTime);
| ^ 553 | } catch (error) {
554 | if (currentTask !== null) {
555 | var currentTime = exports.unstable_now();
View compiled
MessagePort.performWorkUntilDeadline
C:/ReactJs/Source Codes/react-master/node_modules/scheduler/cjs/scheduler.development.js:164
161 | var hasTimeRemaining = true;
162 |
163 | try {
> 164 | var hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
| ^ 165 |
166 | if (!hasMoreWork) {
167 | isMessageLoopRunning = false;
Thank you
First, you're using React so prefer using React handlers like the following :
const nextItem = document.querySelector('.next');
nextItem.addEventListener('click', showNextItem);
becomes :
<button className="next" onClick={showNextitem}>
<span>
<i className="ion-arrow-right-c"></i>
</span>
</button>
you need to read some articles about event handling in react.
useEffect needs an empty array as second param to work like componentDidMount.
useEffect(() => {
document.addEventListener('keydown', keyPress);
// clean up
return () => {
document.removeEventListener('keydown', keyPress);
};
},[])
then as Marc Charpentier has said you add onClick={functionName} to the html element.
The reason that you receive the error is that a functional component does not have lifecycle (unlike class component) and it runs line after line.
which means when this line
nextItem.addEventListener('click', showNextItem);
is executed, the component has not returned any html element and it's not rendered in DOM. it does not exist yet so it's null.
and as you can read from the error message Cannot read property 'addEventListener' of null it can not find addEventListener in null

Bug with react-accessible-accordion

Im using the following npm librarie :
"react-accessible-accordion": "2.3.1",
it is returning an error to me :
ReferenceError: babelHelpers is not defined
(anonymous function)
C:/Users/tabm005/www/node_modules/react-accessible-accordion/dist/umd/index.js:1037
1034 |
1035 | var createReactContext = unwrapExports(lib);
1036 |
> 1037 | var _typeof = typeof Symbol === "function" && babelHelpers.typeof(Symbol.iterator) === "symbol" ? function (obj) {
1038 | return typeof obj === 'undefined' ? 'undefined' : babelHelpers.typeof(obj);
1039 | } : function (obj) {
1040 | return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === 'undefined' ? 'undefined' : babelHelpers.typeof(obj);
View compiled
./node_modules/react-accessible-accordion/dist/umd/index.js.React__default
http://localhost:3000/static/js/bundle.js:121672:10
121669 | /***/ (function(module, exports, __webpack_require__) {
121670 |
121671 | (function (global, factory) {
> 121672 | true ? factory(exports, __webpack_require__(/*! react */ "./node_modules/react/index.js")) :
| ^ 121673 | typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
121674 | (factory((global.reactAccessibleAccordion = {}),global.React));
121675 | }(this, (function (exports,React) { 'use strict';
View source
./node_modules/react-accessible-accordion/dist/umd/index.js
C:/Users/tabm005/www/node_modules/react-accessible-accordion/dist/umd/index.js:5
2 | typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
3 | typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
4 | (factory((global.reactAccessibleAccordion = {}),global.React));
> 5 | }(this, (function (exports,React) { 'use strict';
6 |
7 | var React__default = 'default' in React ? React['default'] : React;
8 |
View compiled
__webpack_require__
C:/Users/tabm005/www/webpack/bootstrap ad42cbaf3c46aaff76f3:678
675 | };
676 |
677 | // Execute the module function
> 678 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
679 |
680 | // Flag the module as loaded
681 | module.l = true;
View compiled
fn
C:/Users/tabm005/www/webpack/bootstrap ad42cbaf3c46aaff76f3:88
85 | console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
86 | hotCurrentParents = [];
87 | }
> 88 | return __webpack_require__(request);
89 | };
90 | var ObjectFactory = function ObjectFactory(name) {
91 | return {
View compiled
./src/components/Summary/summaryAccordion.js
http://localhost:3000/static/js/bundle.js:198742:85
__webpack_require__
C:/Users/tabm005/www/webpack/bootstrap ad42cbaf3c46aaff76f3:678
675 | };
676 |
677 | // Execute the module function
> 678 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
679 |
680 | // Flag the module as loaded
681 | module.l = true;
View compiled
fn
C:/Users/tabm005/www/webpack/bootstrap ad42cbaf3c46aaff76f3:88
85 | console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
86 | hotCurrentParents = [];
87 | }
> 88 | return __webpack_require__(request);
89 | };
90 | var ObjectFactory = function ObjectFactory(name) {
91 | return {
View compiled
./src/components/stepsFormsContainer/stepsFormsContainer.js
http://localhost:3000/static/js/bundle.js:206311:84
__webpack_require__
C:/Users/tabm005/www/webpack/bootstrap ad42cbaf3c46aaff76f3:678
675 | };
676 |
677 | // Execute the module function
> 678 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
679 |
680 | // Flag the module as loaded
681 | module.l = true;
View compiled
fn
C:/Users/tabm005/www/webpack/bootstrap ad42cbaf3c46aaff76f3:88
85 | console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
86 | hotCurrentParents = [];
87 | }
> 88 | return __webpack_require__(request);
89 | };
90 | var ObjectFactory = function ObjectFactory(name) {
91 | return {
View compiled
./src/components/stepsFormsContainer/index.js
C:/Users/tabm005/www/src/components/stepsFormsContainer/index.js:1
> 1 | import StepsFormsContainer from './stepsFormsContainer';
2 |
3 | export default StepsFormsContainer;
4 |
View compiled
▶ 5 stack frames were collapsed.
./src/components/stepperManager/index.js
C:/Users/tabm005/www/src/components/stepperManager/index.js:1
> 1 | import StepperManager from './stepperManager';
2 |
3 | export default StepperManager;
4 |
View compiled
▶ 12 stack frames were collapsed.
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.
I tried several manipulations : remove my node_modules and package-lock.json and re-install the application. I tried a newer version of accordion too and no solution worked for me.
Any Idea ?
I added the babel librairies and that resolved my problem:
"babel": "^6.23.0",
"babel-core": "^6.26.3"

Error in reactjs +materail-ui

I am getting this error while building a simple app which has two routes one to '/' and other to '/search'. I have used various components of material-ui.
The problem is when I route to '/search' the following error is thrown:
I have tried all necessary things but unable to figure out what's wrong?
I am just posting half of code here:
function capitalizeFirstLetter(string) {
28 | process.env.NODE_ENV !== "production" ? (0, _warning2.default)(typeof string === 'string', 'Material-UI: capitalizeFirstLetter(string) expects a string argument.') : void 0;
29 |
> 30 | return string.charAt(0).toUpperCase() + string.slice(1);
31 | } // weak
32 |
33 | function contains(obj, pred) {
View compiled
Typography
node_modules/material-ui/Typography/Typography.js:114
111 | other = (0, _objectWithoutProperties3.default)(props, ['align', 'classes', 'className', 'component', 'color', 'gutterBottom', 'headlineMapping', 'noWrap', 'paragraph', 'type']);
112 |
113 |
> 114 | var className = (0, _classnames2.default)(classes.root, classes[type], (_classNames = {}, (0, _defineProperty3.default)(_classNames, classes['color' + (0, _helpers.capitalizeFirstLetter)(color)], color !== 'default'), (0, _defineProperty3.default)(_classNames, classes.noWrap, noWrap), (0, _defineProperty3.default)(_classNames, classes.gutterBottom, gutterBottom), (0, _defineProperty3.default)(_classNames, classes.paragraph, paragraph), (0, _defineProperty3.default)(_classNames, classes['align' + (0, _helpers.capitalizeFirstLetter)(align)], align !== 'inherit'), _classNames), classNameProp);
115 |
116 | var Component = componentProp || (paragraph ? 'p' : headlineMapping[type]) || 'span';
117 |
View compiled
mountIndeterminateComponent
node_modules/react-dom/cjs/react-dom.development.js:8032
8029 | warning(false, "The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);
8030 | }
8031 | ReactCurrentOwner.current = workInProgress;
> 8032 | value = fn(props, context);
8033 | }
8034 | // React DevTools reads this flag.
8035 | workInProgress.effectTag |= PerformedWork;
View compiled
beginWork
node_modules/react-dom/cjs/react-dom.development.js:8221
8218 |
8219 | switch (workInProgress.tag) {
8220 | case IndeterminateComponent:
> 8221 | return mountIndeterminateComponent(current, workInProgress, renderExpirationTime);
8222 | case FunctionalComponent:
8223 | return updateFunctionalComponent(current, workInProgress);
I see in Typography.js that it use capitalizeFirstLetter for color and align.
Check if you inserted there something that is not a string.

Resources