GatsbyJs and Material-UI css is lost on page refresh - material-ui

I have a gatsby site which runs fine on develop mode but whenever the site is built and deployed and the page is refreshed the site renders erratically.
I suspect the header component which has a window.innerwidth query is the cause.
Here is my code:
export default function Header(props) {
const [state, setState] = useState({ mobileView: true })
const { mobileView } = state
const classes = useStyles()
useEffect(() => {
const setResponsiveness = () => {
return window.innerWidth < 900
? setState((prevState) => ({ ...prevState, mobileView: true }))
: setState((prevState) => ({ ...prevState, mobileView: false }));
};
setResponsiveness();
window.addEventListener("resize", () => setResponsiveness());
return () => {
window.removeEventListener("resize", () => setResponsiveness());
}
}, []);
const MobileMenu = () => {...some code}
const DesktopHeader = () => {...some code}
}
return (
<header>
<AppBar className={classes.root} elevation={0} position='static'>
{mobileView ? <MobileMenu /> : <DesktopHeader />}
</AppBar>
</header>
)
}
```
The link to the deployed site can be found here: [Working Site][1]
[1]: https://brit-tr.com

Related

Uncaught TypeError: Cannot read property 'appendChild' of undefined

I have a following return from my component
<div className="content page-with-map" >
<div className='route-editor'>
<Loader loading={routeSectionsLoadingList}/>
{this.renderRouteSectionsList()}
<div className='route-map-block'>
<MapComponent className='route-map'>
<Pane name='RouteSections' style={{ zIndex: 300 }}>
<RouteSectionsLayer
isAdd={isAdd}
isEdit={isEdit}
linesData={routeSectionsFeaturesList}
selectedLine={selectedSection}
setSelectedLine={this.handleSelectSection}
hoveredLine={hoveredSection}
onMouseOverLine={this.onMouseOver}
onMouseOutLine={this.onMouseOut}
/>
</Pane>
</MapComponent>
</div>
</div>
</div>
);
and here is my MapComponent, where i take children and add some custom props. Also rendering map on condition of higher div added to the DOM:
const cityBounds = CITY_BOUNDS;
// State
const [bounds, setBounds] = useState(cityBounds);
const [renderMap, setRenderMap] = useState(false);
const [zoom, setZoom] = useState();
const leafletContainerRef = useRef(null);
useEffect(() => {
if (leafletContainerRef.current) {
setRenderMap(true);
}
}, [leafletContainerRef.current]);
const onViewportChanged = (viewport) => {
const { zoom } = viewport;
setZoom(zoom);
};
const onBoundsChanged = (bounds) => {
setBounds(bounds);
};
const {
className,
children,
} = props;
let customProps = {};
return (
<div className={classNames('leaflet-container', className)} ref={leafletContainerRef}>
{renderMap ?
<MapContainer
bounds={bounds}
doubleClickZoom={false}
crs={L.CRS.EPSG3395}
onViewportChanged={onViewportChanged}
>
<TileLayer
url="https://vec{s}.maps.yandex.net/tiles?l=map&v=20.07.01-0&x={x}&y={y}&z={z}&scale=1&lang=ru_RU"
subdomains={['01', '02', '03', '04']}
attribution='<a http="yandex.ru" target="_blank">Яндекс</a>'
/>
{React.Children.map(children, child => {
customProps = { ...customProps, onBoundsChanged: onBoundsChanged, bounds: bounds };
return React.cloneElement(child, customProps);
})}
</MapContainer>
: null}
</div>
);
}
And also RouteSectionsLayer component:
export default function RouteSectionsLayer(props) {
const { isEdit = false, selectedLine } = props;
const getLines = () => {
const { onMouseOverLine = () => {}, onMouseOutLine = () => {}, linesData = [] } = props;
return linesData && linesData.length ?
linesData.map((lineFeature, i) => {
const lineIndex = i;
return <Polyline
key={hash(lineIndex)}
pane={'RouteSections'}
positions={lineFeature.geometry
&& lineFeature.geometry.coordinates
&& lineFeature.geometry.coordinates.map(line => line.map(vertex => vertex.map(coordinate => +coordinate)))}
attribution={`${i}`}
lineIndex={lineIndex}
pathOptions={{
color: 'black',
weight: 5,
}}
/>;
})
: null;
};
return (
getLines()
);
}
While rendering i get "Uncaught TypeError: Cannot read property 'appendChild' of undefined". What am i doing wrong?
UPDATE: I tried to rewrote RouteSectionsLayer following core architecture example from docs, now it looks like this:
export default function RouteSectionsLayer(props) {
const leafletContext = useLeafletContext();
const getLinesData = () => {
const { input, linesData = [] } = props;
if (input && input.value) {
return input.value;
}
return linesData;
};
useEffect(() => {
const container = leafletContext.layerContainer || leafletContext.map;
const linesData = getLinesData();
const polyLinesInstances = linesData && linesData.length ?
linesData.map((lineFeature, lineIndex) => {
const latlngs = lineFeature.geometry && coordsToNumbers(lineFeature.geometry.coordinates);
const layerOptions = {
attribution: `${lineIndex}`,
pane: 'RouteSections'
};
const pathOptions = normalRouteSectionStylePathOptions;
const polyLineOptions = {
lineIndex: { lineIndex },
...layerOptions,
...pathOptions
};
return new L.Polyline(latlngs, polyLineOptions)
})
: [];
const layerGroupInstance = new L.LayerGroup(polyLinesInstances);
container.addLayer(layerGroupInstance);
return () => {
container.removeLayer(layerGroupInstance);
};
});
const coordsToNumbers = (lineCoordinates) => {
return lineCoordinates && lineCoordinates.length ?
lineCoordinates.map(line => line.map(vertex => vertex.map(coordinate => +coordinate)))
: null;
};
And the error is still here
well, i found my mistake. In re-wrote RouteSectionsLayer i deleted pane in the options of the polyline:
const layerOptions = {
attribution: `${lineIndex}`,
pane: 'RouteSections' // <-- i deleted this.
};
It seams that the pane 'RouteSections' i created as a child of MapComponent was not found.

react-map-gl-draw addFeatures creating duplicates

Describe the Issue
When feature is deleted and new feature is added for vertices to update. The new feature is created twice. Every time this cycle is repeated.
Function deleteVertex have the the code of this problem.
Actual Result
new duplicate feature is added.
Expected Result
Only 1 new feature should be created.
Reproduce Steps
Add a feature. Remove the Feature any 1 index of coordinates. Remove the old Feature. Add the this new modified version of Feature using addFeatures.
Question
Also I want to know if there is any easy way to add or remove the vertices.
Code
const MapOverLay = ({
type,
viewport,
setViewport,
save,
close,
previousFeatures,
defaultViewPort,
}) => {
const editorRef = useRef(null);
const featureRef = useRef(null);
const locateIconRef = useRef(false);
const [previousFeature, setPreviousFeature] = useState(previousFeatures);
const [mapData, setMapData] = useState({
editor: {
type: previousFeatures.length ? 'Editing' : '',
mode: previousFeatures.length ? new EditingMode() : null,
selectedFeatureIndex: null,
},
});
const onSelect = map => {
if (map.selectedEditHandleIndex !== null) {
featureRef.current = {
type: 'selectedEditHandleIndex',
index: map.selectedEditHandleIndex,
featureIndex: map.selectedFeatureIndex,
};
}
else {
featureRef.current = {
type: 'selectedFeatureIndex',
index: map.selectedFeatureIndex,
};
}
};
const onUpdate = ({ editType, data }) => {
if (editType === 'addFeature') {
const temp_data = makeClone(mapData);
temp_data.editor.type = 'Editing';
temp_data.editor.mode = new EditingMode();
setMapData(temp_data);
}
if (previousFeatures.length) {
setPreviousFeature(data);
}
};
const deleteVertex = () => {
const feature = editorRef.current.getFeatures()[0];
if (feature.geometry.coordinates[0].length !== 2) {
feature.geometry.coordinates[0].splice(featureRef.current.index, 1);
editorRef.current.deleteFeatures(featureRef.current.featureIndex);
editorRef.current.addFeatures(feature);
console.log('Delete');
}
else {
editorRef.current.deleteFeatures(featureRef.current.featureIndex);
}
featureRef.current = null;
};
// console.log(editorRef.current);
const deleteFeature = () => {
if (previousFeature.length) {
setPreviousFeature([]);
}
else {
editorRef.current.deleteFeatures(featureRef.current.index);
}
save([]);
};
const onDelete = () => {
if (featureRef.current !== null) {
switch (featureRef.current.type) {
case 'selectedEditHandleIndex':
deleteVertex();
return;
case 'selectedFeatureIndex':
deleteFeature();
return;
default:
break;
}
}
};
const onSave = map => {
save(map.getFeatures());
};
const getDrawModeStyle = () => {
switch (type) {
case 'Polygon':
return style.polygon;
case 'Point':
return style.point;
}
};
const getDrawModePressedStyle = () => {
switch (type) {
case 'Polygon':
return style.pressed_polygon;
case 'Point':
return style.pressed_point;
}
};
const getDrawMode = () => {
switch (type) {
case 'Polygon':
return new DrawPolygonMode();
case 'Point':
return new DrawPointMode();
}
};
const onToolClick = () => {
if (editorRef.current.getFeatures().length === 0) {
const temp_data = makeClone(mapData);
if (type === temp_data.editor.type) {
temp_data.editor.type = '';
temp_data.editor.mode = null;
setMapData(temp_data);
}
else {
temp_data.editor.type = type;
temp_data.editor.mode = getDrawMode();
setMapData(temp_data);
}
}
};
const locate = map => {
locateIconRef.current = true;
const features = map.getFeatures();
if (features.length) {
const center = centerOfMass(features[0]);
setViewport(prevState => ({
...prevState,
zoom: 10,
longitude: center.geometry.coordinates[0],
latitude: center.geometry.coordinates[1],
}));
}
else {
defaultViewPort();
}
};
const viewPortChangeFromMap = nextViewport => {
locateIconRef.current = false;
setViewport(nextViewport);
};
const _renderDrawTools = () => {
// copy from mapbox
return (
<>
<div className='mapboxgl-ctrl-top-left'>
<div className={['mapboxgl-ctrl-group mapboxgl-ctrl', style.navigation_group_top_left].join(' ')}>
<button
className="mapbox-gl-draw_ctrl-draw-btn"
title="Save"
onClick={() => onSave(editorRef.current)}
/>
<button
id={getDrawModeStyle()}
className={
[
'mapbox-gl-draw_ctrl-draw-btn mapbox-gl-draw_polygon',
mapData.editor.type === type ? getDrawModePressedStyle() : '',
].join(' ')
}
title="Select"
onClick={() => onToolClick()}
/>
<button
className="mapbox-gl-draw_ctrl-draw-btn mapbox-gl-draw_trash"
title="Remove"
onClick={onDelete}
/>
</div>
</div>
<div className='mapboxgl-ctrl-top-right'>
<div className={['mapboxgl-ctrl-group mapboxgl-ctrl', style.navigation_group_top_right].join(' ')}>
<button
className="mapbox-gl-draw_ctrl-draw-btn"
title="Close"
onClick={close}
/>
</div>
</div>
<div className='mapboxgl-ctrl-bottom-right'>
<div className={['mapboxgl-ctrl-group mapboxgl-ctrl', style.navigation_group_bottom_right].join(' ')}>
<button
className="mapbox-gl-draw_ctrl-draw-btn"
title="Focus"
onClick={() => locate(editorRef.current)}
/>
</div>
</div>
</>
);
};
return (
<ReactMapGL
{...viewport}
mapStyle="mapbox://styles/giddyops/ckips5wdw61xb17qs3eorsoj9"
mapboxApiAccessToken={MAPBOX_TOKEN}
onViewportChange={viewPortChangeFromMap}
attributionControl={false}
transitionDuration={1000}
transitionInterpolator={locateIconRef.current ? new FlyToInterpolator() : null}
>
<Editor
ref={editorRef}
mode={mapData.editor.mode}
clickRadius={12}
features={previousFeature.length ? previousFeature : null}
onSelect={onSelect}
onUpdate={onUpdate}
editHandleShape={'circle'}
featureStyle={getFeatureStyle}
editHandleStyle={getEditHandleStyle}
onClick={e => console.log(e)}
/>
{_renderDrawTools()}
</ReactMapGL>
);
};
I have reviewed your code and found out that it could be issue that delete features was finished deleting way after than adding feature.
you can solve this issue by making the following changes:
make deleteVertex function async.
cloning the feature in the first line.
await the editorRef.current.deleteFeatures(featureRef.current.featureIndex);

testing input events with react testing library

I've created a small keypad app in react and I'm trying to test the input event on the app and for some reason I am not getting the expected result. I'm trying to test it to failure and success. The test I'm running is this below, I want to input 1995 (the correct combination), click the unlock button and ultimately have a message return Unlocked! but it only returns Incorrect Code! which should only happen if the code is incorrect or the input field is empty. But it shouldn't be empty as I have filled it out in the test..
here is a codesandbox: https://codesandbox.io/s/quirky-cloud-gywu6?file=/src/App.test.js:0-26
Any ideas?
test:
const setup = () => {
const utils = render(<App />);
const input = utils.getByLabelText("input-code");
return {
input,
...utils
};
};
test("It should return a successful try", async () => {
const { input, getByTestId } = setup();
await act(async () => {
fireEvent.change(input, { target: { value: "1995" } });
});
expect(input.value).toBe("1995");
await act(async () => {
fireEvent.click(getByTestId("unlockbutton"));
});
expect(getByTestId("status")).toHaveTextContent("Unlocked!");
});
the component I'm trying to test
import React, { useState, useEffect } from "react";
import Keypad from "./components/Keypad";
import "./App.css";
import "./css/Result.css";
function App() {
//correctCombination: 1995
const [result, setResult] = useState("");
const [locked, setLocked] = useState("Locked");
const [tries, setTries] = useState(0);
const [hide, setHide] = useState(true);
//Along with the maxLength property on the input,
// this is also needed for the keypad
useEffect(() => {
(function() {
if (result >= 4) {
setResult(result.slice(0, 4));
}
})();
}, [result]);
const onClick = button => {
switch (button) {
case "unlock":
checkCode();
break;
case "clear":
clear();
break;
case "backspace":
backspace();
break;
default:
setResult(result + button);
break;
}
};
const checkCode = () => {
if (result === "1995") {
setLocked("Unlocked!");
setTries(0);
} else if (tries === 3) {
setHide(false);
setLocked("Too many incorrect attempts!");
setTimeout(() => {
setHide(true);
}, 3000);
} else {
setLocked("Incorrect code!");
setTries(tries + 1);
}
};
const clear = () => {
setResult("");
};
const backspace = () => {
setResult(result.slice(0, -1));
};
const handleChange = event => {
setResult(event.target.value);
};
return (
<div className="App">
<div className="pin-body">
<h1>Pin Pad</h1>
<div className="status">
<h2 data-testid="status">{locked}</h2>
</div>
<div className="result">
<input
maxLength={4}
type="phone"
aria-label="input-code"
data-testid="inputcode"
placeholder="Enter code"
onChange={handleChange}
value={result}
/>
</div>
{hide ? <Keypad onClick={onClick} /> : false}
</div>
</div>
);
}
export default App;

waitForEvent is not finding the DOM change after fireEvent is called

I have the following component that I'm trying to test with react-testing-library:
const PasswordIconButton = ({
stateString
}) => {
const { state, dispatch } = useContext(Store);
const showPassword = getObjectValue(stateString, state);
const toggleShowPassword = event => {
event.preventDefault();
dispatch(toggleBoolean(stateString, !showPassword));
};
return (
<Layout
showPassword={showPassword}
toggleShowPassword={toggleShowPassword}
/>
);
};
export default PasswordIconButton;
const Layout = ({
showPassword,
toggleShowPassword
}) => {
return (
<IconButton onClick={toggleShowPassword} data-testid="iconButton">
{showPassword ? (
<HidePasswordIcon data-testid="hidePasswordIcon" />
) : (
<ShowPasswordIcon data-testid="showPasswordIcon" />
)}
</IconButton>
);
};
This works exactly as intended in production. If the user clicks the button then it calls toggleShowPassword() which toggles the value of boolean const showPassword.
If showPassword is equal to false and the user clicks the button, I can see that the <ShowPasswordIcon /> is removed and <HidePasswordIcon /> appears. Both have the correct data-testid attributes set.
I'm attempting to test the component will the following test:
import React from "react";
import {
render,
cleanup,
fireEvent,
waitForElement
} from "react-testing-library";
import PasswordIconButton from "./PasswordIconButton";
afterEach(cleanup);
const mockProps = {
stateString: "signUpForm.fields.password.showPassword"
};
describe("<PasswordIconButtonIcon />", () => {
it("renders as snapshot", () => {
const { asFragment } = render(<PasswordIconButton {...mockProps} />);
expect(asFragment()).toMatchSnapshot();
});
//
// ISSUE IS WITH THIS TEST:
// ::::::::::::::::::::::::::
it("shows 'hide password' icon on first click", async () => {
const { container, getByTestId } = render(
<PasswordIconButton {...mockProps} />
);
const icon = getByTestId("iconButton");
fireEvent.click(icon);
const hidePasswordIconTestId = await waitForElement(
() => getByTestId("hidePasswordIcon"),
{ container }
);
expect(hidePasswordIconTestId).not.toBeNull();
});
});
The shows 'hide password' icon on first click test always fails and I'm not sure why. The mockProps are definitely correct and work perfectly in production.
What am I missing here?
I figured it out... The issue is that I needed to wrap the component in the context provider as const { state, dispatch } = useContext(Store); won't work properly without it.
So I changed the render to:
const { container, getByTestId } = render(
<StateProvider>
<PasswordIconButton {...mockProps} />
</StateProvider>
);`
And now the test passes fine.

Use a custom render for rerender using react-testing-library

I'm using react-testing-library and I have a custom render:
const customRender = (node, ...options) => {
return render(
<ThemeProvider theme={Theme}>
<MemoryRouter>{node}</MemoryRouter>
</ThemeProvider>,
...options
);
};
I can use it successfully for a render in my test but not for a rerender:
test("shows content once data has loaded", () => {
const { queryByTestId, rerender, debug } = render(
<ConnectAccount
currentUser={{
loading: true
}}
/>
);
expect(queryByTestId("content")).toBeNull();
rerender(
<ConnectAccount
currentUser={{
user: {
name: "Test User"
}
}}
/>
);
debug();
});
I get an error TypeError: Cannot read property 'black' of undefined for the rerender. Is there any way for the rerender to use the custom render so I don't have to wrap every rerender in the ThemeProvider?
You need to redifine the rerender method. This should work:
const customRender = (node, options) => {
const rendered = render(
<ThemeProvider theme={Theme}>
<MemoryRouter>{node}</MemoryRouter>
</ThemeProvider>,
options);
return {
...rendered,
rerender: (ui, options) =>
customRender(ui, {container: rendered.container, ...options}),
}
};
Typescript version:
function AppProvider({ children }: { children: React.ReactNode }) {
return (
<OtherProvider>
<ThemeProvider theme={Theme}>
<MemoryRouter>{children}</MemoryRouter>
</ThemeProvider>,
</OtherProvider>
);
}
function renderInProvider(
ui: ReactElement,
options?: Omit<RenderOptions, "wrapper">
) {
return render(<AppProvider>{ui}</AppProvider>, options);
}