How to make a Dynamic dropdown done in React with SQL database - javascript

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 :)

Related

What is the best way to use external JSON file data as a props for landing-section in different pages?

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.

react-slideshow-image package not loading images from google drive

I've been trying for two days to make heads or tails of the react-slideshow-image package. I've installed all the missing dependencies by hand, I tried moving the images folder around (anything outside of src threw an error immediately though...), and I also tried uploading my images to an external google drive and substituting their links for the ones given in the example. I've disabled all other components inside the App.js.
Bottom line: the package only works if I use the image links provided in the example. No other images are ever detected.
Here is my code (copied and pasted from the example):
import { Fade } from "react-slideshow-image";
import "react-slideshow-image/dist/styles.css";
// import images from "./images/homepage";
const fadeImages = [
"https://drive.google.com/file/d/1zAkmE3ZoXgYRjhylfRHCZKUJkUakCrfZ/view?usp=sharing",
"https://drive.google.com/file/d/11Gz-fVv4hiKnfHgEPoLPZ02PlNQY3EYP/view?usp=sharing",
"https://drive.google.com/file/d/1B7WAX020SBZ1Bdq9TpC1ps0-XsdIJwWN/view?usp=sharing"
// "https://images.unsplash.com/photo-1506710507565-203b9f24669b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1536&q=80",
// "https://images.unsplash.com/photo-1536987333706-fc9adfb10d91?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80"
];
export default function App() {
return (
<div className="slide-container">
<Fade>
<div className="each-fade">
<img src={fadeImages[0]} alt="" />
</div>
<div className="each-fade">
<img src={fadeImages[1]} alt="" />
</div>
<div className="each-fade">
<img src={fadeImages[2]} alt=""/>
</div>
</Fade>
</div>
);
}
Original unspalsh image links have been commented out to see if my links work, but they don't. Using images other than the ones provided seems to crash the slider entirely.
screenshot of live server view of my webstie
App.js is rendered correctly, console does not log a sinle glitch.
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
// import reportWebVitals from './reportWebVitals';
// import Carousel from "./components/main/Carousel.js";
// const divStyle = {
// position: "absolute"
// }
ReactDOM.render(
<React.StrictMode>
<App/>
</React.StrictMode>,
document.getElementById('root')
);
What am I doing wrong?
You need to store the images ids and use a different path to get the image url https://drive.google.com/uc?id="<file-id>:
const fadeImages = [
"1zAkmE3ZoXgYRjhylfRHCZKUJkUakCrfZ",
"11Gz-fVv4hiKnfHgEPoLPZ02PlNQY3EYP",
"1B7WAX020SBZ1Bdq9TpC1ps0-XsdIJwWN"
];
const PATH = "https://drive.google.com/uc?id=";
then:
export default function App() {
return (
<div className="slide-container">
<Fade>
{fadeImages.map(src => (
<div className="each-fade">
<img src={`PATH${src}`} alt="" />
</div> ))
}
</Fade>
</div>
);
}

Error: Images Array loop from another images folder in REACT

I want to make shopping app in react but i did wrong thing where i dont know.What is the error?
I want to import images and looping them according to "sku number" but i just fetch header of images. I can't see images, i can't fetch them.
<img src="../src/images/{{$product.sku}}.jpg" alt={product.title} />
This is the fetch code . I have tried and i'm trying different codes for fetching but it doesn't work.
Products.js :
import React, { Component } from "react";
import a from "./a.json";
import "./styles.css";
class Products extends Component {
state = {
products: a.products
};
render() {
const productItems = this.state.products.map(product => (
<div className="col-md-4">
<div
className="thumbnail text-center"
style={{ backgroundColor: "black" }}
>
<a href={product.id} onClick={this.props.handleAddToCart}>
<img src="../src/images/{{$product.sku}}.jpg" alt={product.title} />
</a>
</div>
</div>
));
return <div className="row">{productItems}</div>;
}
}
export default Products;
And the sight of folders:
And the sku numbers for matching with photo's names.
The sight of page
Try changing this line:
<img src="../src/images/{{$product.sku}}.jpg" alt={product.title} />
for:
<img src={`../src/images/${product.sku}.jpg`} alt={product.title} />
In order for you to embed Javascript into any React component, remember to always enclose your code block in {brackets}. Since backticks belong to Javascript syntax, the enclosing brackets must be added.

Trying to display text, but no luck. However, I check my console and see empty divs with p tags. App is not breaking

I am in the process of working on a joke app, which I am building from scratch by myself with no tutorial. Right now, there is a component SportsJokesApi, that pulls in the data from a local json folder (SportsJokesData) I created. This is how it is set up:
const SportsJokesData = [
{
id: "1",
question: "What did the baseball glove say to the ball?",
answer: "Catch ya later!"
}
]
export default Sports Jokes Data
On the landing page, when the user selects the Sports Jokes category, they will be taken to a new page which will display jokes related to sports. Right now, you need to click the button (Click here for a joke) in order for the first joke to display. I would love for the first random joke to already be displaying when the user selects this category and gets taken to that page for the first time.
This is how I have the component set up. In my initial approach I created a separate function called getInitialJoke, which returns a random joke. Then in the render, I created a variable called const {initialJoke} which is this.getInitialJoke(); and then the joke would be displayed. Since state update is asynchronous, I did some safety checking by using initialjoke?.answer. When I go back and run the app, no joke appears and the text does not show up. However, I do see new divs with empty p tags on console. Does anyone know what could be wrong and how I can fix this? Again, I want a joke to already be displaying. The way it is set up in this component, you have to click on the Click Here for a Joke button in order to see the first joke.
import React from 'react'
import SportsJokesData from '../data/SportsJokesData';
import { Link } from 'react-router-dom';
import './Buttons.css';
const initialState = {
randomJoke: {}
};
class SportsJokesApi extends React.Component {
constructor(props) {
super(props);
this.getRandomJoke = this.getRandomJoke.bind(this);
this.state = initialState;
}
getInitialJoke() {
return SportsJokesData[(SportsJokesData.length * Math.random()) << 0];
}
getRandomJoke() {
this.setState({
randomJoke: SportsJokesData[(SportsJokesData.length * Math.random()) << 0]
});
}
render() {
const {randomJoke} = this.state;
const {initialJoke} = this.getInitialJoke();
return (
<React.Fragment >
<div>
<p>{initialJoke?.question}</p>
</div>
<div>
<p>{initialJoke?.answer}</p>
</div>
<div className="flex">
<p>{randomJoke.question}</p>
</div>
<div className="flex">
<p>{randomJoke.answer}</p>
</div>
<div className="flex">
<button class="btn joke" onClick = {this.getRandomJoke}>Click here for joke </button>
</div>
<div className="flex">
<Link to="/ProgrammingJokes">
<button className="btn programming">Programming Jokes</button>
</Link>
</div>
<div className="flex">
<Link to="/DadJokes">
<button className="btn dad">Dad Jokes</button>
</Link>
</div>
<div className="flex">
<Link to="/SpanishJokes">
<button className="btn spanish">Chistes en ñ</button>
</Link>
</div>
<div className="flex">
<Link to="/">
<button className="btn home">Home Page</button>
</Link>
</div>
</React.Fragment >
);
}
}
export default SportsJokesApi;
Perhaps you could call the initialJoke() function in one of the React lifeCycle Events, for example with something like this:
// Add this to your code fellow.
componentDidMount() {
this.getInitialJoke();
}
For more information on the life cycle events and how they work, have a look at this great article, buddy.
React: Component Lifecycle Events

Reactjs and Nodejs

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)
});

Categories