I have a React project and this is my first time using it.
I have a JavaScript in the container that import a JavaScript within the components.
This is my containers file
Restorans.js
import React, { Component } from 'react';
import Restoran from "./components/Restoran/Restoran";
import classes from "./Restorans.module.css";
class Restorans extends Component{
constructor(props){
super(props);
this.state = {
restorans:
[
{id:1, nama: "Restoran A", alamat: "This is address Restoran A", nomorTelepon : "0217352333"},
{id:2, nama: "Restoran B", alamat: "This is address Restoran B", nomorTelepon : "0217352334"},
{id:3, nama: "Restoran C", alamat: "This is address Restoran C", nomorTelepon : "0217352335"}
],
isLoading: true
}
}
componentDidMount() {
console.log("componentDidMount()");
}
shouldComponentUpdate(nextProps, nextState) {
console.log("shouldComponentUpdate()");
}
loadingHandler = () => {
const curretIsLoading = this.state.isLoading;
this.setState({isLoading: !(curretIsLoading)});
console.log(this.state.isLoading);
}
render() {
console.log("render()")
return(
<React.Fragment>
<div className={classes.Title}> All Restoran </div>
<div className={classes.Restorans}>
{this.state.restorans.map(restoran =>
<Restoran
key={restoran.id}
nama={restoran.nama}
alamat={restoran.alamat}
nomorTelepon = {restoran.nomorTelepon}
/>
)}
</div>
</React.Fragment>
);
}
}
export default Restorans;
and this is my components
Restoran.js
import React from "react";
import classes from "./Restoran.module.css";
const Restoran = props => {
return(
<div className={classes.Restoran}>
<h3>
{props.name}
</h3>
<p>
Alamat: {props.alamat}
</p>
<p>
Nomor Telepon: {props.nomorTelepon}
</p>
</div>
)
}
export default Restoran;
My folder library is as follow
When I run npm start on my terminal. I receive this error:
Module not found: Can't resolve './components/Restoran/Restoran' in 'C:\Users\[REDACTED]\projectreact\frontend-projectreact\src\containers\Restorans'
To my own understanding, there shouldn't be any error. I tried to add .js on the end but it still has the same problem. Where did I go wrong?
It looks like you are within the containers directory in Restorans.js.
If you want to access Restoran.js from components, you have to go two levels up and out of containers, so change your import in containers/Restorans.js to:
import Restoran from "./../../components/Restoran/Restoran";
The ../../ part will take you to the root parent directory where both containers and components live as children/sub-directories by moving you up two folders.
As far as CSS, I usually import it one place from in the root <App/> component after a normalizer/CSS Reset.
Firstly,(just an advice) try not to name your files same. I see Restorans.module.css both in Restoran and Restorans. It might get clumsy to do so. And next thing is if you want to import css file
import "../Restoran/Restoran.module.css"
or any specific element then
import {classes} from "../Restoran/Restoran.module.css"
Also , check the path as ,if you are working on Restoran.js then
"../../components/Restoran/Restoran"
.. -> changes to root and then from there you can change your folder and access the required components.
Defining the path as './../../components/Restoran/Restoran' should help.
You use incorrect relative path (in Restorans.js), try:
import Restoran from "../../components/Restoran/Restoran";
Also you can set up aliases to have absolute paths (import Restoran from '#components/Restoran/Restoran')
Related
I keep getting this weird error in my React that says
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `ContactTemplate`.
I tried to remove each of the import to see where the error is, but nothing works.
My ContactTemplate.jsx:
import React from 'react';
import { Container } from '~/components/interface/Container';
import PreviewBar from '~/components/PreviewBar';
import HeroFull from '~/components/HeroFull/HeroFull';
import { Wrapper, Columns, Paragraph, BigText } from './ContactTemplate.styles';
import { Link } from '~/components/interface/Link';
const ContactTemplate = ({ preview }) => {
const data = [
{
name: 'Name 1',
job: 'Bestuursrechts',
phone: '+31 (0) 612345678',
email: 'Email',
link: 'https://www.linkedin.com',
},
{
name: 'Name 2',
job: 'Intellectuele eigendom en contractenrecht',
phone: '+31 (0) 612345678',
email: 'email',
link: 'https://www.linkedin.com',
},
];
return (
<>
<Wrapper>
{preview && <PreviewBar />}
<HeroFull
title="Contact"
intro="We offer ...."
/>
</Wrapper>
<Container>
<Columns>
{data.map(item => (
<div>
<BigText>{item.name}</BigText>
<Paragraph>{item.job}</Paragraph>
<Paragraph>{item.phone}</Paragraph>
<Paragraph>{item.email}</Paragraph>
<Link>{item.link}</Link>
</div>
))}
</Columns>
</Container>
</>
);
};
export default ContactTemplate;
Could someone help me out with this please?
If there are more files needed I'll add them on request.
Most likely you're trying to import { ContactTemplate } from "./ContactTemplate", but you're using export default. At this point you should import ContactTemplate from "./ContactTemplate"
Can you confirm if this is the case?
Can you show the component, where you import and trying to use ContactTemplate?
I solved it myself. The first problem was that my Docker was stuck so I had to restart it. After I restarted it I tried to remove each import individually to see where the problem was and it was the { Link } that needed to be just Link. Thanks everyone else for helping!
I am new to react js. I have created a class extends Component. When I run my code it throws error mentioned that, variables are not defined. I am following a tutorial. This is works for the tutor correctly. But I am getting error.
App.js
import logo from './logo.svg';
import './App.css';
import React from 'react';
import TextCard from './textCard';
class App extends React.Component {
textArr = [
{
id: 1,
name:"Name1",
department:"Computer",
semester :7,
},
{
id:2,
name: "Name2",
department: "Computer",
semester: 7,
},
{
id: 3,
name: "Name3",
department: "Computer",
semester: 7,
}
]
textCards = this.textArr.map((item)=>{
return (
<TextCard key={item.id} name={item.name} department={item.department} semester={item.semester} />
)
})
hideOnClick(){
alert('Hide btn pressed')
}
text1 = "Testing variable access"
render(){
return(
<div className="App">
<h1>My React js</h1>
<h2>React js course from Udemy</h2>
<hr></hr>
<h3>JSX test</h3>
<hr></hr>
<div>{this.text1}</div>
<hr></hr>
<button onClick={this.hideOnClick}>Hide List</button>
<div>
{this.textCards}
</div>
</div>
);
}
}
export default App;
textCard.js
import React from 'react';
import classess from './textCard.module.css';
const TextCard = (props) =>{
return(
<div className={classess.dynamicTest}>
<h2>{props.name}</h2>
<p>{props.department}</p>
<p>{props.semester}</p>
</div>
)
}
export default TextCard;
The Error
Failed to compile.
src\App.js
Line 11:3: 'textArr' is not defined no-undef
Line 34:3: 'textCards' is not defined no-undef
Line 50:3: 'text1' is not defined no-undef
Search for the keywords to learn more about each error.
You need to install and use the #babel/plugin-proposal-class-properties to use class fields. Class fields are not in the Javascript core language yet and you need to tell the Babel compiler how to handle them if you want to use them.
npm install --save-dev #babel/plugin-proposal-class-properties
And add this to your .babelrc.json
"plugins": ["#babel/plugin-proposal-class-properties"]
If your tutorial didn't mention that you need to install this plugin, it is not a good tutorial.
I'm trying to use react-image-annotate but it's giving me this issue when I first try to set it up.
And here's how I'm using it:
import React from 'react'
import ReactImageAnnotate from 'react-image-annotate'
function ImageAnnotator() {
return (
<ReactImageAnnotate
selectedImage="https://images.unsplash.com/photo-1561518776-e76a5e48f731?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80"
// taskDescription="# Draw region around each face\n\nInclude chin and hair."
// images={[
// { src: 'https://example.com/image1.png', name: 'Image 1' },
// ]}
// regionClsList={['Man Face', 'Woman Face']}
/>
)
}
export default ImageAnnotator
I'm using Next.js if that matters
UPDATE 1
I tried using this babel plugin as suggested by Alejandro Vales. It gives the same error as before. Here's the babel key in my package.json:
"babel": {
"presets": [
"next/babel"
],
"plugins": [
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"#babel/plugin-transform-modules-commonjs",
{
"allowTopLevelThis": true
}
]
]
}
I would say that the issue relies in the library itself by what they replied in here (similar bug) https://github.com/UniversalDataTool/react-image-annotate/issues/90#issuecomment-683221311
Indeed one way to fix it I would say is adding babel to the project so you can transform the imports in your project to require automatically without having to change the code on your whole project.
This is the babel package you are looking for https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs
Another reason for this could be an outdated version of your package, as some people report to have this fixed after using a newer version of Create React App (https://github.com/UniversalDataTool/react-image-annotate/issues/37#issuecomment-607372287)
Another fix you could do (a little crazier depending on your resources) is forking the library, creating a CJS version of the lib, and then pushing that to the library, so you and anybody else can use that in the future.
I got a tricky solution!
Problem is that react-image-annotate can only be imported in client-side(SSR got error for import keyword)
So, let react-image-annotate in Nextjs be imported only in client side
(https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr)
in Next Page that needs this component, You can make component like this
import dynamic from "next/dynamic";
const DynamicComponentWithNoSSR = dynamic(() => import("src/components/Upload/Annotation"), { ssr: false });
import { NextPage } from "next";
const Page: NextPage = () => {
return (
<>
<DynamicComponentWithNoSSR />
</>
);
};
export default Page;
Make component like this
//#ts-ignore
import ReactImageAnnotate from "react-image-annotate";
import React from "react";
const Annotation = () => {
return (
<ReactImageAnnotate
labelImages
regionClsList={["Alpha", "Beta", "Charlie", "Delta"]}
regionTagList={["tag1", "tag2", "tag3"]}
images={[
{
src: "https://placekitten.com/408/287",
name: "Image 1",
regions: [],
},
]}
/>
);
};
export default Annotation;
When use PascalCase for the component name the component is not registered by vue. Below is how it looks like
<template>
<div>
<h6>This is a sample reusable component</h6>
</div>
</template>
<script>
export default {
name: "SampleComponent",
data() {
return {
};
}
}
</script>
This is how i am registering components.
import SampleComponent from './components/SampleComponent'
const components:any = {SampleComponent}
const ComponentLibrary = {
install(Vue:any, options = {}) {
for (const componentName in components) {
const component = components[componentName];
Vue.component(component.name, component);
}
}
}
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(ComponentLibrary)
}
export default ComponentLibrary;
While importing the library i get the below error
Unknown custom element: <samplecomponent> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
(found in <Root>)
If i use just 'Sample' then it works. Not sure how to fix this.
Referencing the component name with kebab case in DOM has fixed the isssue. In any other vue project Pascal case worked.
So currently I'm importing a component multiple times with different names.
import Page1 from "./Page/Page"
import Page2 from "./Page/Page"
import Page3 from "./Page/Page"
import Page4 from "./Page/Page"
I'm doing this as I want each instance to have its own set of properties, which then I use <keep-alive> to maintain their state.
I am also using them inside a <component :is="".
I was wondering if there was a way to create multiple instances without multiple import.
Codesandbox:
https://codesandbox.io/s/5x391j8y4x
you will notice that if I switch between the HelloWorlds, that the input will maintain their instances (input will change to what they were holding)
You don't need to use <component> because you only have one component type that you want to use: HelloWorld. <component> is only needed when you want to dynamically render different component types.
The reason why you require <keep-alive> is because the HelloWorld component has local state (msg) which will be lost once the component instance is destroyed.
You will need to use key to force Vue to instantiate a new instance of HelloWorld based on the page, and you need <keep-alive> to prevent each instance from being destroyed when you switch between pages.
Here's an example:
<ul>
<li
v-for="page in pages"
#click="currentPage = page"
:key="page.key">{{ page.title }}</li>
</ul>
<keep-alive>
<hello-world
:key="currentPage.key"
:title="currentPage.title"/>
</keep-alive>
import HelloWorld from './components/HelloWorld'
export default {
name: "App",
components: {
HelloWorld,
},
data() {
const pages = [
{
key: "home",
title: "Home"
},
{
key: "about",
title: "About"
},
{
key: "contact",
title: "Contact"
}
]
const currentPage = pages[0]
return {
currentPage,
pages
}
}
}