How can I use a variable in React JS render method? - javascript

I am learning React JS.
Now, I am using a variable in App.js file and want to use this variable in render() method in index.js file but it's showing me this error:
./src/index.js Line 7: 'bioData' is not defined no-undef
Search for the keywords to learn more about each error.
in App.js file I have this code:
import React from 'react';
import logo from './logo.svg';
import './App.css';
import * as serviceWorker from './serviceWorker';
function Person (props) {
return (
<div className="p1">
<h1>{props.name}</h1>
<h3>{props.skill}</h3>
</div>
);
}
var bioData = (
<div>
<Person name="alex" skill="designer" />
<Person name="shibbir" skill="web developer" />
</div>
);
export default Person;
and In index.js file I have following code:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Person from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(bioData, document.querySelector("root"));
serviceWorker.unregister();
can you tell me why it's showing that erro?

The problem is that you haven't imported bioData into index.js (or defined it locally). In modules, top-level declarations are not globals, modules have their own scope (thankfully). So var bioData in App.js doesn't define a global index.js sees.
If you want to use biodata in index.js, export it from App.js:
export var bioData = {/*...*/};
...and import it into index.js, perhaps on the line where you're importing Person:
import Person, { bioData } from './App';
Note that that's a named export/import. You asked in a comment whether you should use export default bioData; in App.js, but you can't, you already have a default export in App.js (Person). You can have only one default export (or none), and then as many named exports as you like (or none).
Side note: var is obsolete. Use let or const.
Side note 2, re this code:
ReactDOM.render(bioData, document.querySelector("root"));
Assuming you're trying to render to an id="root" element, it should be either document.getElementById("root") (more idiomatic) or document.querySelector("#root"), but not document.querySelector("root") (which looks for a <root>...</root> element).

Related

React index.js Unknown word

I have an index.js file in my root directory but whenever I run npm start i get an Unknown word in index.js error.
How do I fix this problem? Looked online but can't seem to get it running. Since there is very little info about this error.
//index.js
import {createRoot} from 'react-dom/client';
import App from './App'
const root = createRoot(document.getElementById('root'));
root.render(<App />)
can you try this way
import React from 'react';
import ReactDOM from 'react-dom';
import * as ReactDOMClient from 'react-dom/client';
import App from './App';
const root = ReactDOMClient.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
You should use render method imported from 'react-dom'
// index.js
// import {createRoot} from 'react-dom/client';
import ReactDOM from 'react-dom';
import App from './App'
// const root = createRoot(document.getElementById('root'));
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
)
I just found the cause of this error. It was due to an autocompletion mistake. I have a global css file where I set up the css variables I use in this project such as font and background colors.
Said file needs to be imported into the css files that want to access given variables.
/* How it should look like */
#import url('../../../vars.css');
/* How it's not supposed to look like */
#import url('../../../index.js');
I accidentally autocompleted the index.js into the import statement which resulted in the error.

Getting 'React' must be in scope when using JSX

I am new to react and I tried the following code
person.js
const element = <h1>Hello world</h1>;
export default element;
App.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import Person from '../src/person/person';
function Hello() {
return Person.element;
}
class App extends Component {
render() {
return (
<div className="App">
<Hello></Hello>
</div>
);
}
}
export default App;
But getting the below errors
work/my-app/src/person/person.js
3:17 error 'React' must be in scope when using JSX react/react-in-jsx-scope
When I changed to a simple hello word as below, then it works fine.
person.js
const element = 'hello world';
export default element;
I tried with different ways by checking different forum
importing the ReactDom
in person.js changed to module.exports=element
The use of HTML within JS code is known as JSX. The <h1>...</h1> is JSX. You need to import React before you use JSX. Simply shift the import statements before any use of JSX.
person.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import Person from '../src/person/person';
const element = <h1>Hello world</h1>;
export default element;
You need to import React in every file that exports a component (App in this case).
The latest React 17 Version: No need to include React in the scope
If you are struggling with ESlint or run-time CRA warnings, follow these temporary steps to fix until CRA v4 is released: https://github.com/facebook/create-react-app/issues/9850

Module not found :Can't resolve './components/counter' in 'C:/...demo\counter-app\src'

I am totally new to React and i'm following tutorials (Programming with MOSH) in youtube but i'm stuck with this error, unable to resolve after finding similar questions.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import "bootstrap/dist/css/bootstrap.css";
import Counter from './components/counter';
//import * as Counter from './components/counter'; //tried this method too
ReactDOM.render(
<Counter />,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
counter.jsx
import React, { Component } from 'react';
class Counter extends Component {
render() {
return <h1> Hello world</h1>;
}
}
export default Counter;
in command prompt i had done npm install and npm start after deleting package-lock.json but still the same error
folder structure
Thanks in advance.
Move your components folder inside the SRC this will fix it
Either move components folder inside src folder or change the reference in the import statement to '../component/counter'

console.log() above import statements in root file does not execute before import

Consider the root index.js file in a React app that does the following:
console.log("INDEX.JS")
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import { Provider } from 'react-redux';
//Internal Dependencies
import Auth from './containers/Auth';
import store from './store/store';
import ErrorBoundary from './containers/ErrorBoundary';
//Highcharts config
import highchartsConfig from './globalChartConfig';
//Global styles
import './index.css';
highchartsConfig();
render(
<Router>
<Provider store={store}>
<ErrorBoundary>
<Auth />
</ErrorBoundary>
</Provider>
</Router>,
document.getElementById('root')
);
The import statements are executed BEFORE the console.log statement at the top of this file. a console.log at the top of the Auth.js file will be executed first. Why is that?
The following console.log() is the first thing that logs to the console.
// Auth.js
console.log('AUTH')
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
You must scope all import statements at the top. This restriction allows webpack(not only webpack, any module loader actually) to analyze statically what modules are imported by a module and load them before executing its body.
console.log('first import then log')
import { foo } from 'foo'
Putting code above import throws an eslint warning (import/first)
Why inside index.js console.log fires after the imports and inside
auth.js executes in the expected order?
When calling index.js (entry point which will render the entire application) webpack will bundle every module including those required for App and Auth and then call console.log. When you access Auth.js all modules are already bundled so the only thing left to do is to call console.log.
For a detailed explanation

Index.js module imports with webpack

My code is organised as follows:
where,
Resources/ActionLog/Components/Layout.js
import React from 'react';
export default class Layout extends React.Component {
render() {
return (
<p>Test</p>
);
}
}
Resources/ActionLog/Components/index.js
export * from './Layout';
Resources/ActionLog/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Layout from './Components'; // <--- ISSUE HERE.
const app = document.getElementById('app');
ReactDOM.render(
<Layout/>,
app
);
Why does Layout not get imported using this setup??
If i change the line to read,
import Layout from './Components/Layout';
it works fine, but otherwise Layout is always undefined! Even when if i try,
import Layout from './Components/index';
I am using webpack as my module bundler, and have achieved something similar before, I just don't see why/how this is different..
Why does Layout not get imported using this setup??
Layout.js has a default export. However, export * from './Layout.js will only export the named exports (of which there are none). In other words, Components/Layout.js doesn't have any exports at all, so nothing can be imported.
But even if it did have named exports, import Layout from './Components/index'; imports the default export, but Components/index.js doesn't have a default export.
There are a couple of ways this could be solved. The one that makes the most sense is probably to export the default export of Layout.js as named export in Components/index.js. You will presumably have multiple files each exporting a component. I assume Components/index.js should export a map of all these components in which case you have to use named exports.
The changes you have to make:
// in Components/index.js
export {default as Layout} from './Layout';
// in ActionLog/index.js
import {Layout} from './Components'; // use a named import

Categories

Resources