How to place a rendered element in a div in ReactJs - reactjs

I'm new in ReactJs and I only know a few things as of now. I'm trying to create this Google map with directions which is successful
MapRender.js
import React from 'react';
import { render } from 'react-dom';
import Map from './mapProps';
//import './style.css';
const googleMapsApiKey = "API_KEY";
export default function FinalMap() {
const FinalMap = props => {
const {places} = props;
const {
loadingElement,
containerElement,
mapElement,
defaultCenter,
defaultZoom
} = props;
return (
<Map
googleMapURL={
'https://maps.googleapis.com/maps/api/js?key=' +
googleMapsApiKey +
'&libraries=geometry,drawing,places'
}
markers={places}
loadingElement={loadingElement || <div style={{height: `100%`}}/>}
containerElement={containerElement || <div style={{height: "80vh"}}/>}
mapElement={mapElement || <div style={{height: `100%`}}/>}
defaultCenter={defaultCenter || {lat: 25.798939, lng: -80.291409}}
defaultZoom={defaultZoom || 13}
/>
);
};
const places = [
{latitude:14.7539407,longitude:121.0338431},
{latitude: 14.625981794368357,longitude: 121.06170033978614},
]
render(<FinalMap defaultZoom={12} places={places} />, document.getElementById('root'));
}
And this is my App.js
import React from 'react';
import picture1 from '../../src/picture1.jpg';
import RechartBar from '../postlist/Rechart-Bar';
import RechartLine from '../postlist/Rechart-Line';
import driverstat from '../driverprofiles/driverstat';
import AppMap from './Maps/map';
import MapRender from './Maps/MapRender';
function Home() {
return (
<div className="Bodydiv">
<div className="homediv">
<div className="userdiv">
<div className="userdiv-profile">
<div className="userdiv-profile-photo">
<img src={picture1} className="photo" alt="picture1"></img>
</div>
<div className="userdiv-profile-name">
</div>
<div className="userdiv-profile-name">
Name:
</div>
<div className="userdiv-profile-name">
Driver ID:
</div>
<div className="userdiv-profile-name">
Plate Number:
</div>
<div className="userdiv-profile-name">
Status:
</div>
</div>
<div className="userdiv-stats">
Statistics
{driverstat.map((item, index) => {
return (
<li key={index} className={item.cName}>
{item.icon}
</li>
);
})}
<h4 class="view-history">View History</h4>
<input type="button" className="backtodrivers-btn" alt="back" value="Back"/>
</div>
</div>
<div className='mapdiv'>
<MapRender/>
</div>
</div>
<RechartBar/>
<RechartLine/>
</div>
);
}
export default Home;
The problem is It does run but it made my other elements go away because the map was rendered as seen in the last part of my MapRender.js, what I wanted to do is place this in a component and then call that component in my App.js (Similar to what I have done in RechartBar and RechartLine at the end of my App.js.
Thanks

You are replacing entire app with FinalMap component using this line.
Remove this line from MapRenderer.js
render(<FinalMap defaultZoom={12} places={places} />, document.getElementById('root'));
import React from 'react';
import { render } from 'react-dom';
import Map from './mapProps';
//import './style.css';
const googleMapsApiKey = "API_KEY";
export default function FinalMap(props) {
const {
places,
loadingElement,
containerElement,
mapElement,
defaultCenter,
defaultZoom
} = props;
return (
<Map
googleMapURL={
'https://maps.googleapis.com/maps/api/js?key=' +
googleMapsApiKey +
'&libraries=geometry,drawing,places'
}
markers={places}
loadingElement={loadingElement || <div style={{height: `100%`}}/>}
containerElement={containerElement || <div style={{height: "80vh"}}/>}
mapElement={mapElement || <div style={{height: `100%`}}/>}
defaultCenter={defaultCenter || {lat: 25.798939, lng: -80.291409}}
defaultZoom={defaultZoom || 13}
/>
);
};
Then in App.js
import React from 'react';
import picture1 from '../../src/picture1.jpg';
import RechartBar from '../postlist/Rechart-Bar';
import RechartLine from '../postlist/Rechart-Line';
import driverstat from '../driverprofiles/driverstat';
import AppMap from './Maps/map';
import MapRender from './Maps/MapRender';
function Home() {
return (
<div className="Bodydiv">
<div className="homediv">
<div className="userdiv">
<div className="userdiv-profile">
<div className="userdiv-profile-photo">
<img src={picture1} className="photo" alt="picture1"></img>
</div>
<div className="userdiv-profile-name">
</div>
<div className="userdiv-profile-name">
Name:
</div>
<div className="userdiv-profile-name">
Driver ID:
</div>
<div className="userdiv-profile-name">
Plate Number:
</div>
<div className="userdiv-profile-name">
Status:
</div>
</div>
<div className="userdiv-stats">
Statistics
{driverstat.map((item, index) => {
return (
<li key={index} className={item.cName}>
{item.icon}
</li>
);
})}
<h4 class="view-history">View History</h4>
<input type="button" className="backtodrivers-btn" alt="back" value="Back"/>
</div>
</div>
<div className='mapdiv'>
<MapRender places={[
{latitude:14.7539407,longitude:121.0338431},
{latitude: 14.625981794368357,longitude: 121.06170033978614},
]}/>
</div>
</div>
<RechartBar/>
<RechartLine/>
</div>
);
}
export default Home;

Related

React Carousel and onClick events

I'm making a small imdb clone in reactJS and I just managed to add a carousel to the component that renders out movies. The problem is that the clickevent for each movie doesn't work anymore. What's the simplest way to solve this without rewriting the entire component?
I could add a onclick event to the carousel but then i have to return all the neccessary data from the movie component and later send it to moviePage which seems redundant
Home.js
import { React } from "react";
import SearchBox from "./components/SearchBox";
import Movie from "./components/Movie";
import { Carousel } from "react-responsive-carousel";
function Home(props) {
return (
<div className="App">
<div className="row d-flex align-items-center mt-4 mb-4">
<SearchBox
searchValue={props.searchValue}
setSearchValue={props.setSearchValue}
/>
</div>
<h1>Movies</h1>
<div className="block">
<Carousel onClickItem={console.log("you pressed")}>
{props.data.map((movie, index) => {
return (
<Movie
key={movie.id}
movie={movie}
placeMovie={props.placeMovie}
index={index}
/>
);
})}
</Carousel>
</div>
<h1>Recently viewed</h1>
<div className="inline-view">
{props.latestView.map((n) => {
return (
<img
key={n.id}
src={"https://image.tmdb.org/t/p/w500" + n.backdrop_path}
alt={n.poster_path}
/>
);
})}
</div>
</div>
);
}
export default Home;
Movie.js
import React from "react";
import { NavLink } from "react-router-dom";
export default function Movie(props) {
const handleClick = () => {
props.placeMovie(props.index);
};
return (
<div className="image-container d-flex justify-content-start m-3">
<div>
<NavLink onClick={handleClick} to={`/MoviePage`}>
<img
className="image-list"
src={"https://image.tmdb.org/t/p/w500" + props.movie.backdrop_path}
alt={props.movie.path}
/>
</NavLink>
<h4 class="font-weight-bold">{props.movie.title}</h4>
<h5 class="font-weight-light">Score:{props.movie.vote_average}</h5>
</div>
</div>
);
}
Heres the moviepage that displays more info when you click on a movie item
import React from "react";
function MoviePage(props) {
return (
<div>
<div className="card-single">
<div>
<img
className="image-single"
src={"https://image.tmdb.org/t/p/w500" + props.movie.backdrop_path}
alt={props.movie.path}
/>
<div class="card-title">
<h1 class="font-weight-bold">{props.movie.title}</h1>
</div>
<h3 class="card-text">{props.movie.overview}</h3>
<h5 class="font-weight-light">
Language: {props.movie.original_language}
</h5>
<h5 class="font-weight-light">
Release date: {props.movie.release_date}
</h5>
</div>
</div>
</div>
);
}
export default MoviePage;

Why Can't I style this react component

I'm having a problem styling this component. I have added some styles but they are not reflecting. What might be the problem?
import React,{useContext} from 'react'
import "./display.css"
import { AppContext } from '../App'
const Display = () => {
const styles={
backgroundColor:"white"
}
const{type, stateWord,definition,synonyms}=useContext(AppContext)
return (
<div styles={styles} className='container'>
<section styles={styles}>
{stateWord && <div style={{color:"white"}}><h4> Word Type: {type}</h4>
<h4>Definition : {definition}</h4>
<h4>Synonyms:</h4>
{synonyms.map((syn)=>{
return<div><h4>{syn}</h4></div>
})}
</div>
}
</section>
</div>
)
}
export default Display
You have written styles instead of style in your divs. Should be style={styles}.
import React,{useContext} from 'react'
import "./display.css"
import { AppContext } from '../App'
const Display = () => {
const styles={
backgroundColor:"white"
}
const{type, stateWord,definition,synonyms}=useContext(AppContext)
return (
<div style={styles} className='container'>
<section style={styles}>
{stateWord && <div style={{color:"white"}}>
<h4> Word Type: {type}</h4>
<h4>Definition : {definition}</h4>
<h4>Synonyms:</h4>
{synonyms.map((syn)=>{
return<div><h4>{syn}</h4></div>
})}
</div>
}
</section>
</div>
)}
export default Display
It's because you misspelled style:
styles={styles}
should be
style={styles}

Uncaught TypeError: addItem is not a function at onClick (ItemCard.js:16:1)

This is the error I get every time I try and add something to my cart.
Uncaught TypeError: addItem is not a function at onClick (ItemCard.js:16:1).
I cannot figure out what I am doing wrong. I'm new to react so any help would be greatly appreciated.
This is my ItemCard.js
import {useCart} from 'react-use-cart'
const ItemCard = (props) => {
const {addItem}=useCart();
return (
<div className='col-11 col-md-6 col-lg-3 mx-0 mb-4'>
<div class="card p-0 overflow-hidden h-100 shadow" >
<img src={props.img} class="card-img-top img-fluid" alt=""/>
<div class="card-body text-center">
<h5 class="card-title">{props.title}</h5>
<h5 class="card-title">${props.price}</h5>
<p class="card-text">{props.desc}</p>
<buttton class="btn btn-success"
onClick={()=>addItem(props.item)}
>Add to Cart</buttton>
</div>
</div>
</div>
)
}
export default ItemCard```
This is my Cart.js
import React from 'react'
import { useCart } from 'react-use-cart'
import ItemCard from './ItemCard';
const Cart = () => {
const {
isEmpty,
totalUniqueItems,
totalItems,
items,
cartTotal,
updateItemQuantity,
removeItem,
emptyCart,
}=useCart();
if(isEmpty) return <h1 className='text-center'>Your Cart is Empty</h1>
return (
<section className='py-4 container'>
<div className='row justify-content-center'>
<div className='col-12'>
<h5>Cart ({totalUniqueItems}) total Items:({totalItems})</h5>
<table className='table table-light table-hover m-0'>
<tbody>
{items.map((item,index)=>{
return(
<tr key={index}>
<td>
<img src={item.img} style={{height:'6rem'}}/>
</td>
<td>{item.title}</td>
<td>{item.price}</td>
<td>Quantity ({item.quantity})</td>
<td>
<button className='btn btn-info ms-2'
onClick={()=>updateItemQuantity(item.id, item.quantity - 1)}
>-</button>
<button className='btn btn-info ms-2'
onClick={()=>updateItemQuantity(item.id, item.quantity + 1)}
>+</button>
<button className='btn btn-danger ms-2'>Remove Item</button>
</td>
</tr>
)
})}
</tbody>
</table>
</div>
</div>
</section>
)
}
export default Cart```
This is my App.js
import './App.css';
import Header from './Header'
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom'
import Login from './Login'
import Home from './Home';
import Checkout from './Checkout';
import Footer from './Footer';
import Navlinks from './Navlinks';
import Cart from './Cart';
function App() {
return (
<Router>
<div className="App">
<Switch>
<Route path="/checkout">
<Header/>
<Checkout/>
</Route>
<Route path="/login">
<Login/>
</Route>
<Route path="/">
<Header/>
<Navlinks/>
<cartProvider>
<Home/>
<Cart/>
</cartProvider>
<Footer/>
</Route>
</Switch>
</div>
</Router>
);
}
export default App;```
This is my data.js
const data = {
productData:[
{
id:1,
img: vase,
title:'Porcilane flower vase',
desc: '',
price: 46,
},
{
id:1,
img: vase,
title:'Porcilane flower vase',
desc: '',
price: 46,
},
{
id:1,
img: vase,
title:'Porcilane flower vase',
desc: '',
price: 46,
},
{
id:1,
img: vase,
title:'Porcilane flower vase',
desc: '',
price: 46,
},
],
};
export default data;```
In App.js Add
import { CartProvider } from 'react-use-cart';
and warp all in
<CartProvider> <CartProvider/>
For example :
import { CartProvider } from 'react-use-cart';
import './App.css'
import ListContainer from "./component/ListContainer";
function App() {
return (
<>
<CartProvider>
<ListContainer/>
</CartProvider>
</>
);
}
export default App;

React EmblaCarousel - Functions are not valid as a React child

Can someone help. I have this error "Functions are not valid as a React child. This may happen if you return a Component instead of from render."
In codesandbox everything is working but when i place the code in my react app the error appears.
I am new to react so please explain how i can render EmblaCarousel...
import React, { useCallback } from "react";
import ReactDOM from "react-dom";
import EmblaCarouselReact from "embla-carousel-react";
import "components/partials/Carousel/styles.css";
function App() { {
return (
<div className="embla">
<EmblaCarouselReact
htmlTagName="div"
emblaRef={c => (emblaRef = c)}
options={{ loop: false }}
className="embla__carousel"
>
<div className="embla__container">
<div className="embla__slide">
<div className="embla__inner"></div>
</div>
<div className="embla__slide">
<div className="embla__inner"></div>
</div>
<div className="embla__slide">
<div className="embla__inner"></div>
</div>
<div className="embla__slide">
<div className="embla__inner"></div>
</div>
</div>
</EmblaCarouselReact>
<button onClick={() => prev()}>Previous</button>
<button onClick={() => next()}>Next</button>
</div>
);
};
}
export default App;
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
You're using a two curly bracket in here (one inside one) while defining a function, which makes it a function inside another function, rather then defining a component.
The correct code is here:
import React from "react";
import ReactDOM from "react-dom";
import EmblaCarouselReact from "embla-carousel-react";
import "components/partials/Carousel/styles.css";
function App() {
return (
<div className="embla">
<EmblaCarouselReact
htmlTagName="div"
emblaRef={c => (emblaRef = c)}
options={{ loop: false }}
className="embla__carousel"
>
<div className="embla__container">
<div className="embla__slide">
<div className="embla__inner"></div>
</div>
<div className="embla__slide">
<div className="embla__inner"></div>
</div>
<div className="embla__slide">
<div className="embla__inner"></div>
</div>
<div className="embla__slide">
<div className="embla__inner"></div>
</div>
</div>
</EmblaCarouselReact>
<button onClick={() => prev()}>Previous</button>
<button onClick={() => next()}>Next</button>
</div>
);
}
export default App;
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
The embla-carousel-react version you're using is highly outdated. I would recommend you to update to the latest version in order to enjoy the latest features and make sure it's compatible with later React versions:
npm install embla-carousel-react#latest --save
And make use of the useEmblaCarousel hook instead:
import React, { useCallback } from "react";
import ReactDOM from "react-dom";
import useEmblaCarousel from 'embla-carousel-react';
import "components/partials/Carousel/styles.css";
function App() {
const [emblaRef, emblaApi] = useEmblaCarousel({ loop: false });
const prev = useCallback(() => {
if (emblaApi) emblaApi.scrollPrev()
}, [emblaApi])
const next = useCallback(() => {
if (emblaApi) emblaApi.scrollNext()
}, [emblaApi])
return (
<div className="embla">
<div className="embla__carousel" ref={emblaRef}>
<div className="embla__container">
<div className="embla__slide">
<div className="embla__inner"></div>
</div>
<div className="embla__slide">
<div className="embla__inner"></div>
</div>
<div className="embla__slide">
<div className="embla__inner"></div>
</div>
<div className="embla__slide">
<div className="embla__inner"></div>
</div>
</div>
</div>
<button onClick={prev}>Previous</button>
<button onClick={next}>Next</button>
</div>
);
}
export default App;
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Don't forget to add the following to your CSS because this was done inside the legacy EmblaCarouselReact component before the useEmblaCarousel hook came along:
.embla__carousel {
overflow: hidden;
}
Here is the official documentation for usage with React.
Here is the official documentation guide that shows you how to setup previous and next buttons.

Pass state value from one component to another

I have an array in the parent component, and I want to pass this state value to another componenet which will the props for another component.
import React, { Component } from "react";
import Bookings from "./components/Bookings";
import Meals from "./components/Meals";
import Error from "./components/Error";
class App extends Component {
state = {
values: [{ name: "John Doe", date: "2017-09-15" }]
};
handleGuestInfo = () => {
console.log("Here");
//console.log(this.state.name, "here");
};
render() {
return (
<div className="container-fluid">
<center>
<h2>Hacker Hostel</h2>
</center>
<div className="container">
<Bookings onGuestChange={this.handleGuestInfo} />
<Error />
<Meals name={this.state.values} date={this.state.values} />
</div>
</div>
);
}
}
export default App;
import React, { Component } from "react";
class Meals extends Component {
render() {
return (
<div className="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<ol id="list">
<div>
<li className="morning">
Breakfast for {this.props.name} on {this.props.date}
</li>
<li className="afternoon">Lunch for insert_hacker_name</li>
<li className="night">Dinner for insert_hacker_name</li>
</div>
</ol>
</div>
);
}
}
export default Meals;
Any help will be appreciated, I want to get name and date to the meals.js file from app.js, I am able to pass value for function.
You can map over values state and render the Meal component according to that.
class App extends React.Component {
state = {
values: [{ name: "John Doe", date: "2017-09-15" }]
};
handleGuestInfo = () => {
console.log("Here");
//console.log(this.state.name, "here");
};
render() {
return (
<div className="container-fluid">
<center>
<h2>Hacker Hostel</h2>
</center>
<div className="container">
{this.state.values.map(value =>(
<Meals key={value.name} name={value.name} date={value.date} />
))}
</div>
</div>
);
}
}
class Meals extends React.Component {
render() {
return (
<div className="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<ol id="list">
<div>
{this.props.valuy}
<li className="morning">
Breakfast for {this.props.name} on {this.props.date}
</li>
<li className="afternoon">Lunch for insert_hacker_name</li>
<li className="night">Dinner for insert_hacker_name</li>
</div>
</ol>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" />

Resources