How to import self-made component into index.js in React - javascript

I'm learning react and i'm stuck on how to import a self-made component.
So I made this into src/components/Part/Part.jsx
And in my index.js file I import this like that import { Part } from './components/Part/Part.jsx';
const Part = (props) =>{
return (
<p>{props.part + " " + props.exec}</p>
)
}
export default Part

In your import statement remove curly brackets. It will work then. :)
Update this:
import { Part } from './components/Part/Part.jsx';
To:
import Part from './components/Part/Part.jsx';
For better understanding read named exports and default exports here:
https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

If your folder structure like -
src
|_components
|__Part
|__Part.jsx
|__index.js
And want to export the Part.jsx from index.js then you can write this line into the index.js file.
// At src/components/Part/index.js file
export {default} from './Part.jsx';
And now you can import the Part component from anywhere like-
import Part from 'path/to/components/Part';
Update: You can follow the structure this allows you to import the component like import Part from './components/Part' instead of import Part from './components/Part/Part.jsx'.

Related

how to import json data file and use it in a react component?

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";

import all variables from a file.js with an " import './file.js' " summoning

I'm working with the import function, I wish use an import like for css, I mean "import './file.css'" then all the css attributes are diffused in the file. I have tried the same with ReactJS but it fails.
My expectation is to imitate the css import for js files, but it doesn't work.
Here my sandbox
Here is the relevant code:
import React from "react";
import ReactDOM from "react-dom";
impoprt sample from "./sample"
import "./exported.js";
import "./styles.css";
function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{sample[2]}
{text1}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
I'm getting the error at the line when no using the star's import:
{text1}
I'm wondering how make something similar. Any hint would be great,
thanks
The offending code in your sandbox is: import "./exported.js";
One source of confusion is that you are using Create React App, which hides away the webpack magic which allows you to import your CSS files as import "./styles.css";.
This is not how module exports and imports work. I would recommend reading the section on exporting and importing details on exploringjs.com
What you are doing is essentially an empty import, i.e. you are not importing anything, just executing the file.
Empty import: only loads the module, doesn’t import anything. The
first such import in a program executes the body of the module.
import 'src/my_lib';
But here are various ways to import something in a nutshell.
Assumption: your ./exported.js file has the following exports:
// some other code
export { text1, text2 };
export default config;
Then you can import them in various formats
// import only the default export
import config from './exported.js';
// This only imports the export qualified with default, it ignores others
// i.e.
console.log(config); //works
console.log(text1); // fails
console.log(text2); // fails
// import everything the module exports, but as a namespace
import * as myLib from './exported.js';
// usage: all named exports are properties of the myLib object
console.log(myLib.text1); // works
console.log(myLib.text2); // works
console.log(myLib.config); // should not work, unless you have also exported config as a named export
// import only what you need
import { text1, text2 } from './exported.js';
console.log(text1); // works
console.log(text2); // works
// you can also rename them
import { default as x, text1 as a, text2 as b } from './exported.js';
console.log(x); // works --> config
console.log(a); // works --> text1
console.log(b); // works --> text2
You need to do import defaultExport from 'moduleName'; so you can use defaultExport in your code.
Doing import 'moduleName'; will only run the code in the module but not import anything (see MDN for more info)
In your sandbox, doing import sample from 'sample.js'; would do it.
The problem in your code cause a breaking a import, that didn't let include your css file, the problem is importing export.js and sample.js it must include using a correct Destructuring, e.g.:
import React from "react";
import ReactDOM from "react-dom";
import { text1, text2 } from "./exported.js";
import sample from "./sample.js";
import "./styles.css";
Here complete sample Code Sample.
More info about import statement: import
Destructuring assignment statement: destructuring assignment .
Best regards.

react compile error, Module not found

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.

Find file path from a named import in ES6

I'm trying to obtain the file where a named import is loaded in ES6. Let's say i have
import React, {Component} from 'react';
const dummy = () => (
<div>
Hello!
</div>
);
export default dummy;
I'm processing this file and trying to find out from which file the Component import is loaded. As far as i research, i can use require.resolve(), but it only tells me the index file from a module. What i want to know is from which file a named import is loaded... Any idea?

ES2015: Named import translation

I'm following ES2015. I want to translate regular javascript import statements to ES2015 import statement(s).
What I have:
I have javascript import line as below:
var db = require('../config').get('db')
What I've tried:
import { config } from '../config'
const db = config.db
NOTE
config folder has the index.js which I want to load. In the regular var ... = require('...') statement automatically loads index.js if exists. And I want the ES2015 script also automatically loads when imported.
I think what you're looking for is:
import { db } from '../config'
Assuming db is properly export-ed from config.js, that should work.
Just to clarify, there's three main kinds of imports in JS native modules:
Import the whole module:
import * as foo from 'path/to/foo';
const something = foo.something;
Import specific named exports of the module. This works if the module exports the appropriate objects using export statements:
import { something } from 'path/to/foo';
Import the default export of the module. This only works if the module has an export default statement in it:
import thedefaultexport from 'path/to/foo';
It looks like the '../config' module exports a single object with a get() method. If this is the case, import the whole module, like so:
import * as config from '../config';
And get the database like so:
const db = config.get('db');
If possible, you might want to refactor your '../config' module so that it exports db directly.
export {db};
And then you can use the syntax #AsadSaeeduddin suggested:
import {dp} from '../config';

Categories