Why Does My React App Keep Failing To Compile? - javascript

I'm learning react and building a simple straightforward to do list app. However, it keeps throwing this error:
./src/App.js
Line 9:35: 'Todo' is not defined react/jsx-no-undef
Search for the keywords to learn more about each error.
I'm not sure why this error keeps throwing. I have defined my my ToDo js file - I believe I correctly exported it and then correctly imported in the App js file. Am I missing something?
App.Js File:
import React from 'react';
import logo from './logo.svg';
import './App.css';
import ToDo from './ToDo.js'
import DoData from './DoData.js'
function App() {
const val = DoData.map(item => <Todo key = {item.id} item = {item}/>)
return (
{val}
);
}
export default App;
ToDo.js file:
import React from 'react'
function Todo(props){
return(
<div className = "todo-item">
<input type ="checkbox" checked = {props.things.completed}></input>
<p>{props.things.description}</p>
</div>
)
}
export default Todo
DoData.js:
let DoData = [
{
id: 1,
description: "go for a walk",
completed: true
},
{
id: 2,
description: "babysitting",
completed: true
},
{
id: 3,
description: "watch MadMen",
completed: false
},
{
id: 4,
description: "See the mailman",
completed: true
},
{
id: 5,
description: "Say hello to the world",
completed: false
}
]
export default DoData.js

In JavaScript, identifiers are case-sensitive
Check the case of the identifier in your import statement in the file ./App.Js vs the use of it:
import ToDo from './ToDo.js'
<Todo ... />
Notice the difference in casing between Todo & ToDo. You have 2 options to fix this linting error.
Either change your import to:
import Todo from './ToDo.js'
or
change your use to:
`<ToDo ... />`
Note: Also, double check your export statement in the file ./DoData.js.
While the identifier DoData definitely exists, it has no property called js, and so DoData.js will be undefined.

Option 1
Update
import ToDo from './ToDo.js'
to
import Todo from './ToDo.js'
as you are using <Todo key = {item.id} item = {item}/> in your app
Option 2
Update
<Todo key = {item.id} item = {item}/>
to
<ToDo key = {item.id} item = {item}/>
as you are importing component as ToDo
import ToDo from './ToDo.js'
As you are exporting ToDo as default in ToDo.js file, you can use it as any name as you want in your imports anywhere in your app. But make sure when you render the component, it matches the import name at top.

Related

New to JS and testing - trying to get the selector for this code (TestCafe)

Not sure how to get the selector from this code. On the web app it's displayed as a button that has a dropdown after clicked. Trying to create a test step where this button is clicked, but I can't seem to find/create the right selector.
import { ChevronDownIcon } from '/icons';
import PropTypes from 'prop-types';
import React from 'react';
import UserAvailabilityBadgeIcon from '/components/UserAvailabilityBadgeIcon';
const UserLabel = ({ userName }) -> {
return (
<>
<UserAvailabilityBadgeIcon />
<span>{userName}</span>
<ChevronDownIcon />
);
};
UserLabel.propTypes = {
userName: PropTypes.string.isRequired,
};
export default UserLabel;
Keep getting the error code E24 from TestCafe which is element not found

Uncaught error: Objects are not valid as a React child

I'm really new to react, im trying to build an app in that library, however i keep running into this error and i don't know what it does nor how to resolve it.
I'm just trying to pass data from a parent component to a child component, previously i was trying to do that from a fetch and from an array but now it's just basic props and still i get this error.
the parent component
import axios, * as others from 'axios';
import Row from 'react-bootstrap/Row';
import Cerd from "./Cerd";
import movieArray from "./MovieArray";
export function UseFetch(message){
let number = movieArray.length;
console.log(number);
let image = movieArray[0].image;
let text = movieArray[0].title;
let actors = movieArray[0].actors;
const toStringer = text.toString();
console.log(toStringer);
return(
<div className="row-wrapper">
<Row>
<Cerd title="ciao"/>
</Row>
</div>
)
}
the child component:
mport Card from 'react-bootstrap/card';
export default function Cerd(title){
console.log(title);
return(
<div>{title}</div>
)
}
Here's the error:
I already tried to change computer and search for solutions online but nothing changes, I0m not passing an array or an object in the props as it is just a simple string. This is a killer error because it's not the first time that happens to me and i still haven't found what to do when it happens... can somebody help?
EDIT: I was asked to post the movieArray component, so here it is:
const movieArray = [{
title: "ciao",
actors: "celine dion",
image: "./public/logo192.png"
},{
title: "ciao",
actors: "celine dion",
image: "./public/logo192.png"
},{
title: "ciao",
actors: "celine dion",
image: "./public/logo192.png"
}]
export default movieArray;
In react component props passing, you cannot take it like taking from function.
You defined "title" in props of component, but you cannot take it as a variable. You have to take it as shorthand.
// your code;
export default function Cerd(title){
// must be;
\/
export default function Cerd({title}){
Try ({title}) instead of (title).

React internalisation SPA using i18next

I need to translate my app, but i don't knomw how to use useTranslation() in the top-level files (i store there some consts which contain some text). One of this file is
import { useTranslation } from "react-i18next";
const {t} = useTranslation()
export const selectThemeOptions = [
{ value: "choose", text: "Choose theme" },
{ value: "Algebra", text: "Algebra" },
{ value: "Geometry", text: "Geomerty" },
{ value: "Programming", text: "Programming" },
{ value: "Logic", text: "Logic" },
];
so in this case i have an error:
src\Configs\ThemesOfProblems.js
Line 3:13: React Hook "useTranslation" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks
I need this array in my component, and it use in the next fragment :
<Form.Group as={Col} controlId="problemTheme">
<Form.Label>{t("userprofile.theme")}</Form.Label>
<Form.Select
name="theme"
value={values.theme}
onChange={handleChange}
isValid={touched.theme && !errors.theme}
isInvalid={!!errors.theme}
onBlur={handleBlur}
>
{selectThemeOptions.map((el, index) => {
return <option key={index} value={el.value}> {el.text} </option>
})}
</Form.Select>
</Form.Group>
And i've got a lot of such situations, i don't have any ideas how to do it
Basically it says it has to be called in a react component. It could be called in a functional component where you return your jsx or a class component that has a render method in it. If you call the function outside of one of these, then you will get this error.
You called const {t} = useTranslation(); outside of a React component, your selectThemeOptions file seems to be regular JavaScript due to the absence of JSX or a returning statement with your HTML.
Here is the correct way to do it:
/* Everything above this point is considered top-level, hence using your `useTranslation()` hook here would cause an error */
const Component = (props) => {
const { t } = useTranslation();
}
export default Component;
Here is a way to organise your translations:
• Your src folder should contain an i18n.js file with the following code:
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import en from "../locales/en.json";
import ru from "../locales/ru.json";
const isReturningUser = "lang" in localStorage; // Returns true if user already used the website.
const savedLanguage = JSON.parse(localStorage.getItem("lang")); // Gets persisted language from previous visit.
// Get previously used language in case of returning user or set language to Russian by default.
const language = isReturningUser ? savedLanguage : "ru";
const resources = {
en: {
translation: en,
},
ru: {
translation: ru,
},
};
i18n.use(initReactI18next).init({
resources,
lng: language,
keyseparator: false,
interpolation: {
escapeValue: false,
},
});
export default i18n;
Your src folder should contain a locales folder with json files of the languages your application uses. Example: ru.json and en.json:
{
"choose": "Выбрать",
"chooseATheme": "Выбрать тему",
"algebra": "Алгебра",
"geometry": "Геометрия",
"programming": "Программирование",
"logic": "Логика",
}
Your component should look like this – note that the translations are in json files instead of your React component – :
import React from "react";
import { useTranslation } from "react-i18next";
const Component = (props) => {
const { t } = useTranslation();
const selectThemeOptions = [
{ value: t("choose"), text: t("chooseATheme") },
{ value: t("algebra"), text: t("algebra") },
{ value: t("geometry"), text: t("geometry") },
{ value: t("programming"), text: t("programming") },
{ value: t("logic"), text: t("logic") },
];
return( //Your UI )
}
export default Component;
This way, your translations wouldn't be hard-coded on your selectThemeOptions and will adapt to whichever translation your json locales contain.
Please tell me if this works.
Edit: If you want a concrete example of implementation of my solution here it is: https://github.com/YHADJRABIA/ecommerce/tree/main/src
Edit2: There might be a better solution of doing this, this is merely what worked for me.
Edit3: Following Nikita's comment, here's a solution to use the translation function outside of a react component —How to use react-i18next inside BASIC function (not component)?
P.S. Since you are from Belarus I assume that you want your translation to be made in Russian since Belarusian isn't as widely spoken.

Failed to compile. 'Hi' is not defined no-undef in a new .js file (TaskList.js) (react js component)

TaskList.js
import React from 'react';
export default () => {
return {
<p>
Hi
</p>
};
}
I wonder why couldn't I use the HTML code here in this TaskList.js file in order to make the word "Hi" appear in the front end (localhost:3000) ?
I also found the following error in the front end:
Failed to compile
src\TaskList.js
Line 6:9: 'Hi' is not defined no-undef
Search for the keywords to learn more about each error.
and here's another file that's related to TaskList.js
App.js
import logo from './logo.svg';
import './App.css';
import React from 'react';
import TaskList from './TaskList.js';
function App() {
const tasks = [
{id: 0, description: 'do this', done: false},
{id: 1, description: 'do that', done: false}
];
return (
<div>
<TaskList />
</div>
);
}
export default App;
I came up with the above code as I followed the instructor of a course named "Web Development for Blockchain". Unfortunately, he hasn't answered this question for me yet. So, I post this question here as I really need help from you guys on StackOverflow.
Return like this (change the {} with () )
return (
<p>
Hi
</p>
)

Bundle.js not recognizing one of my files?

Please bear with me because I am a javascript newbie, and just starting to learn react.
I am trying to make a small app but I keep getting an error that one of my files is not found... specifically this:
bundle.js:56 Uncaught Error: Cannot find module "./components/search_bar"
My file structure is that I have my index.js in a folder called src, then my search bar(search_bar.js) in a folder called components. I have triple checked the spelling on them but I continue to get this error.
This is my index.js
import SearchBar from './components/search_bar';
import React from 'react';
import ReactDOM from 'react-dom';
//Create a componant (some /HTML)
const API_KEY = 'AIzaSyC3Z3qTpvAacDLYEIxaueKflFJbWvdIHsw';
const App = () => {
return (
<div>
<SearchBar />
</div>
);
}
// Put that componant on the page (the DOM)
ReactDOM.render(<App />, document.querySelector('.container'));
And this is my search_bar.js
import React, { Component } from 'react';
class SearchBar extends Component {
contructor(props) {
super(props);
// when user updates the search bar this term will get updated.
this.state = { term: ''};
}
render() {
//update state
//use set state everywhere besides constructor!!
return (
<div>
<input onChange={event => this.setState({term: event.target.value})}
/>
Value of the input: {this.state.term}
</div>
);
}
}
export default SearchBar;
Any Ideas as to what I am doing wrong here?
Can you confirm the following directory structure?
my_project/src/index.js
my_project/src/components/search_bar.js
It seems like your current directory structure might instead look like this:
my_project/src/index.js, my_project/components/search_bar.js
AHHH I left an 's' out of constructor... so search_bar.js was unable to compile. I have been looking at this for about an hour now...

Categories

Resources