I'm new to react and confused about how to import, export, and render components. I have a fakeData.json file located in the same src/components folder as the component I'm trying to render. Here is the index.html
<body>
<div id="root"></div>
</body>
Here is the index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Here is the app.js
import './App.css';
import './components/WatchlistTable.js';
import 'rsuite/lib/styles/index.less';
function App() {
return <WatchlistTable />
}
export default App;
Here is where I get confused in src/components/WatchlistTable.js. It is a rsuite table. I try to import the fakeData.json file, which is located in the same components folder, like this:
import fakeData from 'fakeData.json';
But it gives error like "Module not found: Can't resolve fakeData.json". So I try another way.
import {fakeData} from 'fakeData.json';
But it gives same error. In the Visual Studio Code editor I notice message like: "there is no fakeData.json in the public folder."
So I make a copy and put it there. Now VSC error disappears but other error remains.
The fakeData.json file looks like this:
[
{
"id": 1,
"avartar": "url/128.jpg",
blah blah blah...
},
]
So I try another way. I change fakeData.json in components folder to fakeData.js and add
const fakeData = [
But same error. So I try:
const fakeData = require('fakeData.js');
But same error. Suggestions?
EDIT: Per Ridik, I now have this in WatchlistTable.js
import React from 'react';
import fakeData from 'fakeData';
And I have
export default fakeData;
at the end of the fakeData.js file. But still getting same error:
./src/components/WatchlistTable.js
Module not found: Can't resolve 'fakeData' in
'C:\Users\Greg\Projects\react-demos\backtester-rsuite\src\components'
You can not directly import your json array from the JSON file in react. To achieve that you must store your JSON array in a variable and then export default your JSON array. By Doing this you can easily import it in your component.
FakeData.js
const fakeData = [
{
"id": 1,
"avartar": "url/128.jpg",
blah blah blah...
},
]
export default fakeData // you must export it to use in another file.
Then in any component use it like
import fakeData from './Destination_of_file/fakeData.js'
or
Way 2 // recomended
import fakeData from './Destination_of_file/fakeData'
In your import statement you have to provide the relative path of the file. Otherwise it looks into public directory in your project. And also instead of using named import syntax use default import syntax. i.e., in your case use below statement to import that json file in your component.
import jsonFile from "./fakeData.json";
I have a parent directory that contains children directories, where each contains an SVG component and I only need to import some of them. I'm currently importing all the components I need by doing this:
import FacebookIcon from 'project/icons/Facebook';
import TwitterIcon from 'project/icons/Twitter';
import DiscordIcon from 'project/icons/Discord';
import MediumIcon from 'project/icons/Medium';
import YoutubeIcon from 'project/icons/Youtube';
However this seems very verbose. Is there a less verbose way of doing this?
I thought about destructuring, but I wasn't sure how to do this since each file is in a different folder.
Typically, you want to import similar components from a single source (you will get auto-complete too):
import {
FacebookIcon,
TwitterIcon,
DiscordIcon,
DiscordIcon,
MediumIcon,
YoutubeIcon,
} from "project/icons";
// Usage
<FacebookIcon/>
// Same
import Icons from './project/icons';
// Usage
const Icon = Icons.FacebookIcon;
<Icon/>
To achieve this, create index.js file in project/icons and make named export for each of the components.
export { default as FacebookIcon } from "./FacebookIcon";
...
I am trying to share logic components between a React appliacation and a React Native application with a similar structure as shown below:
-source
|-appLogic
|-logicComponent1.js
|-logicComponent2.js
|-moreAppLogic
|-moreLogic.js
|-appviews
|-reactView.js
|-reactNativeView.js
I have a problem during the import of modules in the logic components.
The reactView.js will import the logic components like this:
import {moreLogic} from "appLogic/moreAppLogic/moreLogic.js"
whereas the reactNativeView.js will import the same file like this:
import {moreLogic} from "../appLogic/moreAppLogic/moreLogic.js"
My problem arises in the case of moreLogic.js importing for example logicComponent1. Since react, in the moreLogic.js, will want something like this:
import {logicComponent1} from "appLogic/logicComponent1.js"
and react-native will want:
import {logicComponent1} from "../logicComponent1.js"
I have tried to do the import in moreLogic.js both ways but if I do it the react way, the native app cant find the file and vice versa..
Is there a way to go around this problem?? I cannot change the file structure, that is really not an option.
put package.json file in source/appLogic with the following content:
{
"name": "appLogic"
}
After that you can use import {moreLogic} from "appLogic/moreAppLogic/moreLogic.js" in both react js and react native
I got this error in my browser
Error in ./src/App.js
Module not found: ./components/todo in C:\Users\James\Desktop\react\src
This is what I got in my editor
import {TodoForm, TodoList} from './components/todo'
http://imgur.com/a/8YLod
I even tried import {TodoForm, TodoList} from './components/todo/' I wonder what's wrong.
Imports work on a per module basis for most loaders/bundlers. In other words, you'll need to import the form and list by doing the following:
import { TodoForm } from './components/todo/TodoForm'
import { TodoList } from './components/todo/TodoList'
As a side note, see https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export to make sure that you're exporting the components correctly. The curly braces around your import works for a named export as opposed to a default export.
In order to just import all files from the directory you must have an index.js file that exports everything from the directory
Which in your case the index.js file would look like this
Export * from 'TodoForm'
Export * from 'TodoList'
Note if the export statement doesn't work see this answer to fix the import / export statement
Do you think, when you wrote import {TodoForm, TodoList} from './components/todo', in TodoForm should be value than you exported from file TodoForm.js, and similarly with TodoList? It's don't works.
You should do import from some file. When you wrote from './components/todo' you tried doing import from todo directory. I guess, in egghead video that import works, because, they have index.js file in todo directory. And in this file they do export for every component separately. Try to add index.js file in todo directory with the following contents:
export * from './TodoForm.js';
export * from './TodoList.js';
it's will work.
So the thing is that when you do
import {TodoForm, TodoList} from './components/todo'
What happends is that your compiler will by default search the components TodoForm and TodoList from the index.js file since you have not mentioned explicitly which files to point to
So if in index.js you add something like
export * from './components/todo/TodoForm';
export * from './components/todo/TodoList';
Your approach will work.
I am trying to make ReactJS work with rails using this tutorial. I am getting this error:
Uncaught ReferenceError: React is not defined
But I can access the React object in browser console
I also added public/dist/turbo-react.min.js as described here and also added //= require components line in application.js as described in this answer to no luck. Additionally,
var React = require('react') gives the error:
Uncaught ReferenceError: require is not defined
Can anyone suggest me on how to resolve this?
[EDIT 1]
Source code for reference:
This is my comments.js.jsx file:
var Comment = React.createClass({
render: function () {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
{this.props.comment}
</div>
);
}
});
var ready = function () {
React.renderComponent(
<Comment author="Richard" comment="This is a comment "/>,
document.getElementById('comments')
);
};
$(document).ready(ready);
And this is my index.html.erb:
<div id="comments"></div>
If you are using Babel and React 17, you might need to add "runtime": "automatic" to Babel config.
In .babelrc config file this would be:
{
"presets": [
"#babel/preset-env",
["#babel/preset-react", {"runtime": "automatic"}]
]
}
I got this error because I was using
import ReactDOM from 'react-dom'
without importing react, once I changed it to below:
import React from 'react';
import ReactDOM from 'react-dom';
The error was solved :)
I was able to reproduce this error when I was using webpack to build my javascript with the following chunk in my webpack.config.json:
externals: {
'react': 'React'
},
This above configuration tells webpack to not resolve require('react') by loading an npm module, but instead to expect a global variable (i.e. on the window object) called React. The solution is to either remove this piece of configuration (so React will be bundled with your javascript) or load the React framework externally before this file is executed (so that window.React exists).
If you are using Webpack, you can have it load React when needed without having to explicitly require it in your code.
Add to webpack.config.js:
plugins: [
new webpack.ProvidePlugin({
"React": "react",
}),
],
See http://webpack.github.io/docs/shimming-modules.html#plugin-provideplugin
Possible reasons are 1. you didn't load React.JS into your page, 2. you loaded it after the above script into your page. Solution is load the JS file before the above shown script.
P.S
Possible solutions.
If you mention react in externals section inside webpack configuration, then you must load react js files directly into your html before bundle.js
Make sure you have the line import React from 'react';
Try to add:
import React from 'react'
import { render } from 'react-dom'
window.React = React
before the render() function.
This sometimes prevents error to pop-up returning:
React is not defined
Adding React to the window will solve these problems.
Adding to Santosh :
You can load React by
import React from 'react'
I know this question is answered. But since what worked for me isn't exactly in the answers, I'll add it here in the hopes that it will be useful for someone else.
My index.js file looked like this when I was getting Uncaught ReferenceError: React is not defined.
import {render} from 'react-dom';
import App from './App';
render(<App />, document.getElementById("root"));
Adding import React from 'react'; at the top of the file fixed it.
Now my index.js looks like this and I don't get any error on the console.
import React from 'react';
import {render} from 'react-dom';
import App from './App';
render(<App />, document.getElementById("root"));
Please note I made no change in webpack.config.js or anywhere else to make this work.
import React, { Component, PropTypes } from 'react';
This may also work!
If you're using TypeScript, make sure that your tsconfig.json has "jsx": "react" within "compilerOptions".
I was facing the same issue.
I resolved it by importing React and ReactDOM like as follows:
import React from 'react';
import ReactDOM from 'react-dom';
I got this error because in my code I misspelled a component definition with lowercase react.createClass instead of uppercase React.createClass.
I got this error because I used:
import React from 'react';
while working with React, Typescript and Parcel
Changing it to:
import * as React from 'react';
Solved the problem as suggested by https://github.com/parcel-bundler/parcel/issues/1199#issuecomment-381817548
Sometimes the order of import can cause this error, if after you have followed all the steps above and still finds it hard on you, try making sure the react import comes first.
import React from 'react'
import { render } from 'react-dom'
before any other important you need to make.
The displayed error
after that import react
Finally import react-dom
if error is react is not define,please add ==>import React from 'react';
if error is reactDOM is not define,please add ==>import ReactDOM from 'react-dom';
To whom using CRA and ended up to this question, can use customize-cra and react-app-rewired packages to override babel presets in CRA.
To do this, create a config-overrides.js in the root and paste this code snippet in it.
const { override, addBabelPreset } = require('customize-cra');
module.exports = override(
addBabelPreset('#emotion/babel-preset-css-prop'),
addBabelPreset([
'#babel/preset-react',
{
runtime: 'automatic',
importSource: '#emotion/react',
},
]),
);
And update scripts in package.json with the ones below.
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test --env=jsdom",
I got this because I wrote
import react from 'react'
instead of
import React from 'react'