I am new to react and node , i have kept my JSON file in the server and using node i am fetching it . I need to render it in react component .
problem statement : -
Simple website in react that gets data from server , data can be simple JSON file kept in server . ON click of list item from nav menu , you should get the data from JSON .
Eg:
if you click home link , you should get title and content displayed
if you click on about , you should get title and content displayed
if you click on contact , you should get title and content displayed.
/* JSON file */
{
"home":{"title":"Welcome to home page","content": "welcome to the webpage."},
"about":{"title":"we are a venture funding firm","content":"Lets work together to achieve ideas and profits"},
"contact":{"title":"Below is the address to get in touch","content": "<div>Street no 10</div><div>Domlur</div><div> Bangalore</div><div> Pin 560037</div>"},
"recent":{"title":"Welcome to the news section","newsArray":[{"title":"we are live on October","news": "The website is live on feb"},{"title":"UI courses launched","news": "we have introduced a UI course live now"}] }
}
/**** React Code ******/
import React, { Component } from 'react';
import logo from './logo.svg' ;
import './App.css' ;
import './style.css' ;
class App extends Component {
render() {
return (
<div className="wrapper">
<div className="banner">
<img width = "960px" height = "200px" src= {require('./images/banner.jpg')}/>
<h2> A simple layout using css and html</h2>
</div>
<div id="main">
</div>
<div className="menu">
<h2>Side Menu</h2>
<ul>
<li>Home</li>
<li>About Us</li>
<li>Contact Us</li>
<li>Recent News</li>
</ul>
</div>
<div className="copyright">
<p>Copyright 2010, Some Company</p>
</div>
</div>
);
}
}export default App;
/***** Node code *****/
var fs = require('fs');
var obj;
fs.readFile('dataFile.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
console.log(obj.home)
});
Related
I am new to reactJS and I need an answer for this confusing problem.
I have a landing page that I want to use in my home and contact page. What I want is to send external JSON info as props to these pages and every time I create new page.
I have an external JSON file and I want to add it as a props to my landing page file
What is the best practice to do so, should I save within a state and send it as a props or send it directly as a props
JSON File:
{
"landing page" : {
"home": {
"id":1,
"image": "../media/video/Ai Motion5.mp4",
"title" : "MyAkbar for IT consultant & Services",
"description":"Boost up Your Works With our Services. My Incrediable Team is Here to Save Your Time and Money.",
"buttonOne": "Get A Demo"
},
"Contact" : {
"id":2,
"image": "../media/video/Ai Motion5.mp4",
"title" : "Contact",
"description":"sdadasdskdjaskljdas Team is Here to Save Your Time and Money.",
"buttonOne": "Get A Demo"
}
}
}
Home file:
import React, { Component } from 'react'
import LandingPage from "./landingPage/LandingPage"
import WaveSection from './waveSection/WaveSection'
import MyReview from "./reviewSection/MyReview"
import './styles/style.css'
import data from '../../json/data.json';
class Home extends Component{
render(){
return(
<div id='home' className='home'>
<LandingPage
title = {data['landing page'].home.title}
img = {data['landing page'].home.image}
description ={data['landing page'].home.description}
btn = {data['landing page'].home.buttonOne}
/>
<WaveSection/>
<MyReview/>
</div>
)
}
}
export default Home
Contact File:
import React, { Component } from 'react'
import video from '../../media/video/Ai Motion.mp4';
class Contact extends Component{
render(){
return(
<section className='contact-section landingPage-section'>
<div className="container">
<video autoPlay muted loop="True" id='myVideo' src={video}></video>
</div>
</section>
)
}
}
export default Contact
I will go with the first option (not storing it in state) as this data is static and the app does not modify it directly.
I'm building a react app using facebook's:
https://github.com/facebookincubator/create-react-app
I´m new to react and I havent done a dropdown menu before. I have read a lot in the web and I figure I maybe need to use the select and options tags?
I want to have 4 image buttons as I call Main menu (three of the buttons will be able to navigate directly to the picked page).
The last image button will show an undermenu with 12 options pages to go to.
Option Option Option Option
Undermenu
12 options
I´m unsure where I shall begin, right now I have done some coding before I knew I needed to connect it to the SQL database.
App.js:
import React, { Component } from 'react';
import './sass/style.scss';
import Admin from "./components/routes/Admin";
import DropdownMenu from "./components/DropdownMenu";
class App extends Component {
render() {
return (
<div className="App">
<Admin />
<DropdownMenu />
<p className="TEST"> lorem imsum </p>
</div>
);
}
}
export default App;
DropdownMenu.js component:
import React from 'react';
import main_menu_home from '../images/Buttons/main_menu_home.png';
import main_menu_dragons from '../images/Buttons/main_menu_dragons.png';
import main_menu_dragon_test from '../images/Buttons/main_menu_dragon_test.png';
import main_menu_fortune_cookie from '../images/Buttons/main_menu_fortune_cookie.png';
const DropdownMenu = props => (
<header>
<nav>
<div className="dragonMenu-container">
<div className="dragonMenu">
<ul>
<li>
<img
id="Home"
className="Main_home"
src={main_menu_home}
alt="Home_button_image"
/>
</li>
<li>
<img
id="Dragons"
className="Main_Dragons"
src={main_menu_dragons}
alt="Dragons_button_image"
/>
</li>
<li>
<img
id="Dragon_test"
className="Main_Dragon_test"
src={main_menu_dragon_test}
alt="Dragon_test_button_image"
/>
</li>
<li>
<img
id="Fortune_cookie"
className="Main_fortune_cookie"
src={main_menu_fortune_cookie}
alt="Fortune_cookie_button_image"
/>
</li>
</ul>
</div>
</div>
</nav>
</header>
);
export default DropdownMenu;
Here the code just display four images which it gets from the images/Buttons folder. Maybe you don´t need so many imports and can get all the images with just a proper link to the image but I donno how to.
I think I need a global variable that pointing where all my images are so I can just have to invoke said variable to access the folder where the pictures are.
Ideas?
But back to the Dropdown problem:
I guess I need to create a table in my Sql?
But I donno how.
My problem is that I think of all things at the same time I need to do, but can´t easy myself to do one thing at the time.
I have more code for when I before fetched all from another table if you want to see that code as well.
Any questions, feel free to ask away :)
// Dragoness
UPDATED 18 sep 2019:
Right now, I have come this far:
I can now talk to the SQL database with react and print out some data from the SQL database itself. My problem now is that I just see broken images, does anyone have a solution for my problem?
What I see on the browser
My SQL database menus table with 4 columns
What I wrote in the browse tag to enter my data
Where I have MainMenu.js file and where I want the Buttons images from
App.js:
import React, { Component } from 'react';
import './sass/style.scss';
import Admin from "./components/routes/Admin";
import DropdownMenu from "./components/DropdownMenu";
import MainMenu from "./components/MainMenu";
class App extends Component {
render() {
return (
<div className="App">
<Admin />
<DropdownMenu />
<MainMenu />
<p className="TEST"> lorem imsum </p>
<div><img src='./images/Buttons/main_menu_home.png'/> </div>
</div>
);
}
}
export default App;
fetchMenu.php:
<?php
/* This file fetches current menus . */
include_once 'database.php';
$statement = $pdo->prepare("SELECT * FROM menus ORDER BY picUrl ASC");
$statement->execute();
$data = $statement->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($data, JSON_PRETTY_PRINT);
?>
MainMenu.js:
import React, { Component } from 'react';
import "../App.scss";
class DropDownMenu {
id: 0;
picUrl: "";
linkUrl: "";
isSubmenu: "";
}
class MainMenu extends Component {
constructor(props) {
super(props);
this.state = {
allMenus: []
}
}
fetchAllMenus = () => {
fetch("http://localhost/dragonology/server/fetchMenu.php")
.then(response => response.json())
.then(data => {
console.log(data);
this.setState({ allMenus: data });
});
}
componentDidMount() {
this.fetchAllMenus();
}
render() {
let menu = this.state.allMenus.map((item) => {
return (<div key={item.id}><img src={item.picUrl} alt="dropdownmenu_main_and_under"/> - {item.linkUrl} - {item.isSubmenu}</div>)
});
console.log(menu);
return (
<div>{menu}</div>
);
}
}
export default MainMenu;
Thank you in advance
// Dragoness
Updated 19 sep 2019 with solution
I got some tips from those links:
I changed my images folder to be in the public instead of in src:
getting broken image in React App
Started to see a pattern that most of the tables with an image inside have some kind of "name" column, at least it worked for me:
https://www.youtube.com/watch?v=lTyks6s6b6E
All my success steps I took:
Fixed:
1. I added a folder called images inside the public folder.
2. Added one image of the main menu that I called home.
3. Went to the SQL database, deleted the old rows I tried to display the
data from that you can see on the browse tab that was inside the table
menus.
4. Added another column called picName. Took it as a varchar with 60 in
lengh.
5. Changed the settings on the picUrl to be a varchar with the lengh of
255 instead of 100 that I had before.
6. I did a test using the insert tab selection to add a row with the image
link I had before with the dot dot slash and it worked!.
7. Added 15 more rows(all main and undermenu buttons with its data).
8. After that I changed the folder structure again to have images/Buttons
and added all the button images that I had inside the src folder before.
9. Deleted all the images that were on the old folder.
10. Fixed: App.js took away the import of the DropDownMenu.js component and that it didnt print out my DropDownMenu.js component anymore.
App.js:
import React, { Component } from 'react';
import './sass/style.scss';
import Admin from "./components/routes/Admin";
import MainMenu from "./components/MainMenu";
class App extends Component {
render() {
return (
<div className="App">
<Admin />
<MainMenu />
<p className="TEST"> lorem imsum </p>
<div><img src='./images/Buttons/main_menu_home.png'/> </div>
</div>
);
}
}
export default App;
I couldn´t add the images of how my SQL database look now instead of before/where I find my images now in what folder because am new in Stack Overflow and don´t have enough reputation apperely. But those above are the steps I took to solve my problem :)
I have a small Blaze event handling as below;
Template.navigation.events({
// Collapse menu in mobile mode after click on element
'click #side-menu a:not([href$="\\#"])': function(){
if ($(window).width() < 769) {
$("body").toggleClass("show-sidebar");
}
}
});
UI looks like:
import React from 'react';
import {render} from 'react-dom';
export default class Navbar extends React.Component {
render() {
return (
<aside id="menu">
<div id="navigation">
<ul className="nav" id="side-menu">
</ul>
</div>
</aside>
)
}
}
I just to convert the Blaze event to React function, so that all works same in React as it is working in Blaze Event handling.
The answer might be simple, but I am a newbie to React (16.2) so I expect soft corner.
<template lang="html">
<div class="">
<ul>
<li>{{ this.anArray.model }}</li>
</ul>
</div>
</template>
<script>
import db from '../firebase/init.js';
var link = db.ref('cars').child('-KoKST99e110OZs6g111');
var thedata = link.once('value').then(function(snapshot){return snapshot.val()});
export default {
name: 'view',
firebase: {
anArray:thedata
}
}
</script>
I trying to get the object inside that path on firebase database but is answer unknown. the connection is good, the problem is how Im doing it. Help!
I am having a bear of a time getting my VueJs app to render data from an external API. I've attempted to search for a similar issue, but everything I've found has been of no help.
I'm using the the USDA's nutrition database. When I run the code below, I can see through dev tools that my getNutrients function is making a successful call to the database when I click the button, yet my v-for element won't render any data. If I attempt to simply render nutrients from my data object, I'm able to render all of the raw JSON, just not when I try to render singular items within the v-for element.
Any help with getting the render to work would be greatly appreciated.
Thank you in advance
<template>
<div>
<button #click="getNutrients">Click</button>
<ul>
<li v-for="nutrient in nutrients">{{nutrient.nutrient_id}}</li>
</ul>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'home',
data () {
return {
nutrients: {}
}
},
methods: {
getNutrients: function () {
axios.get('https://api.nal.usda.gov/ndb/nutrients/?format=json&api_key=DEMO_KEY&nutrients=205&nutrients=204&nutrients=208&nutrients=269')
.then(response => {this.nutrients = response.data})
}
}
}
</script>
If it helps, I'm using the Vue Webpack template through the Vue-CLI.
The API's returning a report object, which contains an array of foods, each of which contains an array of nutrients, so you'd need to loop through the foods, then through the nutrients in each food:
<ul>
<li v-for="food in foods">
<h2>{{food.name}}</h2>
<ul>
<li v-for="nutrient in food.nutrients">{{nutrient.nutrient_id}}</li>
</ul>
</li>
</ul>
axios.get(url).then(response => {
this.foods = response.data.report.foods
})