Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
113
rated 0 times [  119] [ 6]  / answers: 1 / hits: 20426  / 7 Years ago, tue, september 12, 2017, 12:00:00

This data is in its own .js file I want to be able to use it all over my app how can I?



   const posts = [{
username: lenard,
avi: https://scontent-sjc2-1.cdninstagram.com/t51.2885-15/e35/20905417_730036297205402_7461293070093385728_n.jpg,
}]


I tried importing it into my App.js and passing it down as a prop



import posts from './data/posts'; //the js file with the data
import Posts from './components/Posts/Posts'; // the component I want to use it in
class App extends Component {
render() {
return (
<div className=App>
<Navigation />
<Posts posts={posts}/>
</div>
);
}
}


When I try to use posts (data) in my Posts.js component I get the error posts is not defined when I try to map through it



{posts.map((item) =>


but I do not understand why its not defined if I passed it down as a prop.


More From » reactjs

 Answers
5

You should export the posts in your js file in order to import it in other files:



export const posts = [{
username: lenard,
avi: https://scontent-sjc2-1.cdninstagram.com/t51.2885-15/e35/20905417_730036297205402_7461293070093385728_n.jpg,
}]


Then you can use



import {posts} from './data/posts';


Here is a working example:

https://www.webpackbin.com/bins/-KtsA8KTKvwxTUo2qlW8



If you want to export default you will need to create the consts and then export it:



const posts = [{
username: lenard,
avi: https://scontent-sjc2-1.cdninstagram.com/t51.2885-15/e35/20905417_730036297205402_7461293070093385728_n.jpg
}];

export default posts;


And import it regularly:



import posts from './data/posts';


https://www.webpackbin.com/bins/-Kts8LJQBS4I1pprHiSo


[#56503] Sunday, September 10, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradleymoisesy

Total Points: 121
Total Questions: 105
Total Answers: 95

Location: Nepal
Member since Mon, Jan 4, 2021
3 Years ago
bradleymoisesy questions
Wed, Dec 22, 21, 00:00, 2 Years ago
Tue, Jun 1, 21, 00:00, 3 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
Thu, Jan 16, 20, 00:00, 4 Years ago
;