I have made a react app, here is my code and three components:
App.js
import React from "react";
import "./App.css";
import mediumCompo from "./mediumCompo";
import ldComp from "./Components/ldComp";
function App() {
const viewportContext = React.createContext({});
const ViewportProvider = ({ children }) => {
const [width, setWidth] = React.useState(window.innerWidth);
const [height, setHeight] = React.useState(window.innerHeight);
const handleWindowResize = () => {
setWidth(window.innerWidth);
setHeight(window.innerHeight);
};
React.useEffect(() => {
window.addEventListener("resize", handleWindowResize);
return () => window.removeEventListener("resize", handleWindowResize);
}, []);
return (
<viewportContext.Provider value={{ width, height }}>
{children}
</viewportContext.Provider>
);
};
const useViewport = () => {
const { width, height } = React.useContext(viewportContext);
return { width, height };
};
const MyComponent = () => {
const { width } = useViewport();
const breakpoint = 900;
return width < breakpoint ? <mediumCompo/> : <ldComp/>;
};
return (
<>
<h1>Hello</h1>
<ViewportProvider>
<MyComponent />
</ViewportProvider>
</>
);
}
export default App;
ldComp.jsx
import React from 'react'
const ldComp = (
<>
<h1>LD</h1>
</>
);
export default ldComp;
mediumCompo.jsx
import React from 'react'
function mediumCompo() {
return (
<>
<h1>MD</h1>
</>
);
}
export default mediumCompo;
i cannot see thisone in rendering website when i zoom in/out..
i did made this kind of website few days back and i copied my code from right there,
also it was working fine just 2 hours ago but now the main problem i can see is :
as you can see no matter where i put my components it never gets used!!
i even tried to use this exactly after <h1>Hello</h1> in my App.js
still not working!!!
>Solution :
It’s working after fixing these few mistakes.
All your React component names MUST be started with a capital letter:
ldComp->LdCompmediumCompo->MediumCompo
Your LdComp is not a function. It was just a const expression. Need to be corrected to be a Const Function Expression:
import React from 'react'
const LdComp = () => (
<>
<h1>LD</h1>
</>
);
export default LdComp;
Working Demo:
