Broken code? Why has it stopped working - javascript

When the page loads initially the header should not be visible but when a user begins to scroll the header should appear.
What do I expect to see?
The header should not be visible until a user begins to scroll
What do I see now
The header is showing when the page first loads and it is not supposed to be showing. It is only not working as expected in Chrome, and it is working in Safari.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
hide: false
};
}
handleHover = () => {
this.setState({
hide: true
});
};
componentDidMount() {
window.addEventListener("scroll", this.handleHover);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.handleHover);
}
render() {
return (
<div>
{this.state.hide ? (
<div
style={{
width: "100%",
height: "120px",
margin: "0 auto",
position: "absolute"
}}
>
<div
style={{
zIndex: "0",
position: "absolute",
marginLeft: "120px",
marginTop: "6px"
}}
>
<img className="Logo" src={Logo} alt="logo" />
</div>
<div className="menuContainer">
<nav>
<Link to="/" className="linkTitle" href="">
Home
</Link>
<Link to="/shop" className="linkTitle" href="">
Shop
</Link>
<a className="linkTitle" href="#aboutus">
About
</a>
<a className="linkTitle" href="">
Contact Us
</a>
<a className="linkTitle" href="">
As seen
</a>
</nav>
</div>
</div>
) : null}
<div className="picContainer">
<div
style={{ backgroundImage: `url(${hairImage})` }}
className="picSection one"
/>
<div className="picSection two" />
<div className="picSection three" />
<div className="picSection four" />
<div className="picSectionL five" />
</div>
</div>
);
}
}

https://codesandbox.io/s/zlyqyvjzjl
There you go. Make sure you can actually scroll. If you div is too small to scroll, it won't trigger the event.
{this.state.hide ? null : <div>some item</div>}
Here is the full code:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
hide: true
};
}
handleHover = () => {
console.log("hello");
this.setState({
hide: false
});
};
componentDidMount() {
window.addEventListener("scroll", this.handleHover);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.handleHover);
}
render() {
return (
<div style={{ height: "2000px" }}>
{this.state.hide ? null : (
<div
style={{
width: "100%",
height: "120px",
margin: "0 auto",
position: "absolute"
}}
>
<div
style={{
zIndex: "0",
position: "absolute",
marginLeft: "120px",
marginTop: "6px"
}}
>
logo
</div>
</div>
)}
<div className="picContainer">hello</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Related

React-slick - how to change custom arrow colour based on the page number

There are 2 custom arrows which are previous-arrow and next-arrow
There are also total 3 pages with 3 slides per page
What I want to do is whenever the page is the first page/last page, the previous arrow/next arrow will apply filter in svg, which means the previous arrow/next arrow will become black color
<img
…
filter:
"invert(3%) sepia(7%) saturate(7029%) hue-rotate(94deg) brightness(86%) contrast(93%)"
}}
/>
For example, if it’s the first page, the previous arrow will be filtered while next arrow will NOT be filtered.
Is it possible to do it?
App.js
import "./styles.css";
import React from "react";
import Slider from "react-slick";
import ArrowPrevious from "./arrow-previous.svg";
import ArrowNext from "./arrow-next.svg";
const ArrowButton = ({ imgSrc, imgAlt, onClick }) => {
return (
<button
onClick={onClick}
style={{ backgroundColor: "transparent", border: "none" }}
>
<img
src={imgSrc}
alt={imgAlt}
style={{
width: "50px",
height: "50px",
filter:
"invert(3%) sepia(7%) saturate(7029%) hue-rotate(94deg) brightness(86%) contrast(93%)"
}}
/>
</button>
);
};
export default function App() {
const settings = {
dots: true,
infinite: false,
speed: 500,
slidesToShow: 3,
slidesToScroll: 3,
prevArrow: <ArrowButton imgSrc={ArrowPrevious} imgAlt="previous-button" />,
nextArrow: <ArrowButton imgSrc={ArrowNext} imgAlt="next-button" />,
beforeChange: (current, next) => {
console.log(next);
}
};
return (
<div>
<Slider {...settings}>
<div>
<h3>1</h3>
</div>
<div>
<h3>2</h3>
</div>
<div>
<h3>3</h3>
</div>
<div>
<h3>4</h3>
</div>
<div>
<h3>5</h3>
</div>
<div>
<h3>6</h3>
</div>
<div>
<h3>7</h3>
</div>
</Slider>
</div>
);
}
Codesandbox
https://codesandbox.io/s/focused-dubinsky-9onwe?file=/src/App.js
See codesandbox
https://codesandbox.io/s/inspiring-austin-k9i86?file=/src/App.js:510-527
You just have to look for the onClick !== null
I broke your arrows into 2 separate components though i.e. ArrowButtonNext and ArrowButtonPrevious
const ArrowButtonPrevious = ({ imgSrc, imgAlt, onClick }) => {
return (
<button
onClick={onClick}
style={{ backgroundColor: "transparent", border: "none" }}
>
<img
src={imgSrc}
alt={imgAlt}
style={{
width: "50px",
height: "50px",
filter:
onClick === null
? "invert(93%) sepia(7%) saturate(7029%) hue-rotate(94deg) brightness(86%) contrast(93%)"
: "none"
}}
/>
</button>
);
};
const ArrowButtonNext = ({ imgSrc, imgAlt, onClick }) => {
return (
<button
onClick={onClick}
style={{ backgroundColor: "transparent", border: "none" }}
>
<img
src={imgSrc}
alt={imgAlt}
style={{
width: "50px",
height: "50px",
filter:
onClick === null
? "invert(93%) sepia(7%) saturate(7029%) hue-rotate(94deg) brightness(86%) contrast(93%)"
: "none"
}}
/>
</button>
);
};
I have Checked on Code sandbox and inspect the arrow ,you can change only background Color or else you need to import arrow icon from Material UI or Bootstrap

Image not displaying in React

I'm having an issue getting an image to appear within my React project. I've done it before and actually copied the same exact code to put it into my project, but for some reason nothing is showing up. I looked in the console and inspected the image and it's showing that there is something there, but just not rendering somehow. Nothing I search for online has a similar issue so I'm wondering if I'm just missing something, and that's what causing it not to render.
Here is the parts of my file that pertains to my question.
import React from 'react';
import { Link } from 'react-router-dom';
import Button from '../../components/Spinner/Button';
import ATABanner from '../../../public/Images/ATAbanner-flip.png';
import ATADouble from '../../../public/Images/ATAdouble-1.png';
import ATASingle from '../../../public/Images/ATAsingle-1.png';
import '../../StyleSheets/AdContract.css';
import '../../StyleSheets/Button.css';
export default class CustomerPage extends React.Component{
constructor(props){
super(props);
this.state = {
QuoteID: this.props.match.params.id,
CustomerFirst: "",
CustomerLast: "",
CurrStep: 1,
StoreList: [],
StoresSelected: [],
AdSize: "",
AdSelected: "",
}
}
... extra stuff and methods here
AdSizeHandler(e){
console.log(e.target.id);
switch(e.target.id){
case "SINGLE": this.setState({AdSize: e.target.id});
break;
case "DOUBLE": this.setState({AdSize: e.target.id});
break;
case "BANNER": this.setState({AdSize: e.target.id});
break;
}
}
RenderAdSelected(){
let img = null;
let ad = this.state.AdSize;
if(ad == "SINGLE"){
img = (
<img id="ad-image-single" name='ADSingle' src={ATASingle} alt="" width="100%" scrolling="no"/>
)
}else if(ad == "DOUBLE"){
img = (
<img id="ad-image-double" name='ADDouble' src={ATADouble} alt="" width="100%" scrolling="no"/>
)
}else if(ad == "BANNER"){
img = (
<img id="ad-image-banner" name='ADBanner' src={ATABanner} alt="" width="100%" scrolling="no"/>
)
}
return img;
}
render(){
return(
<div id="CustomerContainer" style={{width: '100%', height: '100%'}}>
<div id="CustomerContent" className="fade-in" style={{textAlign: 'center', width: '100%', height: '100%', overflowY: 'auto'}}>
<div id="Welcome" style={{marginTop: '5%'}}>
<p style={{fontSize: '35px', fontWeight: 'bold'}}>Hello, {this.state.CustomerFirst + " " + this.state.CustomerLast}</p>
<p style={{fontSize: '20px', color: 'orange'}}><b>Your Quote Is Almost Ready!</b></p>
</div>
<div style={{marginTop: '5%', color: '#0F9D58', fontSize: '37px'}}>
<p><b>Step: {this.state.CurrStep}</b></p>
</div>
<div id="InnerContainer" style={{width: '80%', marginLeft: 'auto', marginRight: 'auto'}}>
{this.RenderStoreSelect(this.state.CurrStep)}
<div id="ad-select">
<div className="fade-in" id="ad-prompt">
<p style={{fontSize: '20px'}}><b>Please Select Your Ad Size</b></p>
</div>
<div id="ad-buttons" style={{display: 'inline-block', marginTop: '2%'}}>
<span style={{display: 'flex'}}>
<Button name="SINGLE" color="G-green" click={this.AdSizeHandler.bind(this)}></Button>
<Button name="DOUBLE" color="G-green" click={this.AdSizeHandler.bind(this)}></Button>
<Button name="BANNER" color="G-green" click={this.AdSizeHandler.bind(this)}></Button>
</span>
</div>
<div>
<img id="adImage" name='ADSingle' src={ATASingle} alt="" width="100" height="100"/>
</div>
</div>
</div>
{this.ConfirmQuote()}
</div>
</div>
)
}
}
Here is proof that it's retrieving the image:
If anyone has any idea what I'm possibly doing wrong, please let me know. Thanks.
I found out the reason for this issue. The problem is that I am in a different route than the home route '/'. I solved my problem by doing this instead: <img id="adImage" name='ADSingle' src={`/${ATASingle}`} alt="" width="100" height="100"/>

infinite scroll not working properly in React

I am using infinite scroll plugin for react.js and for some reason it is not working the way it is supposed to work.
The problem is that all the requests are made at once when the page loads, and not like for example a request should be made for each time I scroll.
My code looks like below:
import React from 'react';
import {Route, Link} from 'react-router-dom';
import FourthView from '../fourthview/fourthview.component';
import {withRouter} from 'react-router';
import {Bootstrap, Grid, Row, Col, Button, Image, Modal, Popover} from 'react-bootstrap';
import traineeship from './company.api';
import Header from '../header/header.component';
import InfiniteScroll from 'react-infinite-scroller';
require('./company.style.scss');
class Traineeship extends React.Component {
constructor(props) {
super(props);
this.state = {
companies: [],
page: 0,
resetResult: false,
hasMore: true,
totalPages: null,
totalElements: 0,
};
}
componentDidMount() {
this.fetchCompanies(this.state.page);
}
fetchCompanies = page => {
let courseIds = '';
this.props.rootState.filterByCourseIds.map(function (course) {
courseIds = courseIds + '' + course.id + ',';
});
traineeship.getAll(page, this.props.rootState.selectedJob, courseIds.substring(0, courseIds.length - 1), this.props.rootState.selectedCity).then(response => {
if (response.data) {
const companies = Array.from(this.state.companies);
if(response.data._embedded !== undefined){
this.setState({
companies: companies.concat(response.data._embedded.companies),
totalPages: response.data.page.totalPages,
totalElements: response.data.page.totalElements,
});
}
if (page >= this.state.totalPages) {
this.setState({hasMore: false});
}
} else {
console.log(response);
}
});
};
render() {
return (
<div className={"wrapperDiv"}>
{/*{JSON.stringify(this.props.rootState)}*/}
<div className={"flexDivCol"}>
<div id="header2">
<div style={{flex: .05}}>
<img src="assets/img/icArrowBack.png" onClick={() => this.props.history.go(-1)}/>
</div>
<div style={{flex: 3}}>
<Header size="small"/>
</div>
</div>
<div id="result">
<div className={"search"}>
<h2 style={{fontSize: 22}}>Harjoittelupaikkoja</h2>
<p className={"secondaryColor LatoBold"} style={{fontSize: 13}}>{this.state.totalElements} paikkaa löydetty</p>
</div>
<div className={"filters"}>
<h5 style={{marginTop: '30px', marginBottom: '10px'}} className={"primaryColor"}>
<strong>Hakukriteerit</strong></h5>
{
this.props.rootState.filters.map((filter, key) => (
<div key={key} className={"filter"}>{filter.title}</div>
))
}
</div>
<div className={"searchResults"}>
<h5 style={{marginTop: '30px', marginBottom: '10px'}} className={"primaryColor"}>
<strong>Hakutulokset</strong></h5>
<InfiniteScroll
pageStart={0}
loadMore={this.fetchCompanies}
hasMore={this.state.hasMore}
loader={<div className="loader" key={0}>Loading ...</div>}
useWindow={false}
>
{
this.state.companies.map((traineeship, key) => (
<div id={"item"} key={key}>
<div className={"companyInfo"}>
<div className={"heading"}>
<div id={"companyDiv"}>
<p className={"LatoBlack"} style={{
fontSize: '18px',
lineHeight: '23px'
}}>{traineeship.name}</p>
</div>
{
traineeship.mediaUrl == null
? ''
:
<div id={"videoDiv"}>
<div className={"youtubeBox center"}>
<div id={"youtubeIcon"}>
<a className={"primaryColor"}
href={traineeship.mediaUrl}>
<span style={{marginRight: '3px'}}><Image
src="http://www.stickpng.com/assets/images/580b57fcd9996e24bc43c545.png"
style={{
width: '24px',
height: '17px'
}}/></span>
<span> <p style={{
fontSize: '13px',
lineHeight: '24px',
margin: 0,
display: 'inline-block'
}}>Esittely</p></span>
</a>
</div>
<div id={"txtVideo"}>
</div>
</div>
</div>
}
</div>
<div className={"location"}>
<div id={"locationIcon"}>
<Image src="assets/img/icLocation.png"
style={{marginTop: '-7px'}}/>
</div>
<div id={"address"}>
{
traineeship.addresses.map((address, key) => {
return (
<a href={"https://www.google.com/maps/search/?api=1&query=" + encodeURI("Fredrikinkatu 4, Helsinki")}>
<p key={key} className={"primaryColor"} style={{fontSize: '13px'}}>{address.street}, {address.city}</p>
</a>
)
})
}
</div>
</div>
<div className={"companyDescription"}>
<p className={"secondaryColor"} style={{
fontSize: '14px',
lineHeight: '20px'
}}>{traineeship.description}</p>
</div>
<div>
{
traineeship.images.map((image, key) => {
return (
<img id={"thumbnail"} width={"100%"}
src={image.url}
style={{
width: '80px',
height: '80px',
marginRight: '10px',
marginBottom: '10px'
}}
alt=""
key={key}
/>
)
})
}
</div>
<div className={"companyContacts"} style={{marginTop: '20px'}}>
<p className={"contactInfo"}>URL: {traineeship.website}</p>
<p className={"contactInfo"}>Email: {traineeship.email}</p>
<p className={"contactInfo"}>Puh: {traineeship.phonenumber}</p>
<p className={"contactInfo"}>Contact: {traineeship.contact}</p>
</div>
</div>
</div>
))
}
</InfiniteScroll>
</div>
</div>
</div>
</div>
);
}
}
export default withRouter(Traineeship);
What can I do so I can eliminate all the request are made when the page is load, I mean this is even worse sending let say 20 request one after another within a second or so.
Any suggestion what is wrong with my code?
by removing useWindow={false} it is working now!
Update: Haven't seen that you are using react-infinite-scroller. If you want to build the loader yourself, see my previous answer. With the plugin you can set a threshold.
The answer lies in here: Question: Infinite Scrolling
What you basically need to do is to set a variable in state, isLoading: false, and change it when data comes in via fetch, when data loading done set it back to false. In your infinite scroll function check (this.state.isLoading).

Uncaught (in promise) TypeError: Cannot read property 'companies' of undefined

I would like to have a list of items with infinite scroll and I am using this package https://github.com/CassetteRocks/react-infinite-scroller but in the documentation there is nothing mentioned how the fetching function looks like.
In my code I have it like this:
this.state = {
companies: [],
page: 0,
resetResult: false,
};
fetchCompanies(page){
traineeship.getAll(page).then(response => {
if (response.data) {
this.setState({ companies: this.state.companies.concat(response.data._embedded.companies) });
} else {
console.log(response);
}
});
}
componentDidMount() {
this.fetchCompanies(this.state.page);
}
<InfiniteScroll
pageStart={0}
loadMore={this.fetchCompanies}
hasMore={true || false}
loader={<div className="loader" key={0}>Loading ...</div>}
useWindow={false}
>
{
this.state.companies.map((traineeship, key) => (
<div id={"item"} key={key}>
<div className={"companyInfo"}>
<div className={"heading"}>
<div id={"companyDiv"}>
<p style={{
fontSize: '18px',
lineHeight: '18px'
}}>{traineeship.name}</p>
</div>
{
traineeship.video === null
? ''
:
<div id={"videoDiv"}>
<div className={"youtubeBox center"}>
<div id={"youtubeIcon"}>
<a className={"primaryColor"}
href={traineeship.mediaUrl}>
<span style={{ marginRight: '3px' }}><Image
src="http://www.stickpng.com/assets/images/580b57fcd9996e24bc43c545.png"
style={{
width: '24px',
height: '17px'
}} /></span>
<span> <p style={{
fontSize: '13px',
lineHeight: '18px',
margin: 0,
display: 'inline-block'
}}>Esittely</p></span>
</a>
</div>
<div id={"txtVideo"}>
</div>
</div>
</div>
}
</div>
<div className={"location"}>
<div id={"locationIcon"}>
<Image src="assets/img/icLocation.png" style={{ marginTop: '-7px' }} />
</div>
<div id={"address"}>
<a href={"https://www.google.com/maps/search/?api=1&query=" + encodeURI("Fredrikinkatu 4, Helsinki")}>
<p className={"primaryColor"}
style={{ fontSize: '13px' }}>{traineeship.city}(show in
map)</p>
</a>
</div>
</div>
<div className={"companyDescription"}>
<p className={"secondaryColor"} style={{
fontSize: '14px',
lineHeight: '20px'
}}>{traineeship.description}</p>
</div>
<div className={"companyContacts"} style={{ marginTop: '20px' }}>
<p className={"contactInfo"}>URL: {traineeship.website}</p>
<p className={"contactInfo"}>Email: {traineeship.email}</p>
<p className={"contactInfo"}>Puh: {traineeship.phonenumber}</p>
<p className={"contactInfo"}>Contact: {traineeship.contact}</p>
</div>
</div>
</div>
))
}
</InfiniteScroll>
Full message error:
Uncaught (in promise) TypeError: Cannot read property 'companies' of
undefined
at eval (traineeships.component.js:71)
Edit: (I no longer have the error but loadmore seems not trigger at all)
import React from 'react';
import {Route, Link} from 'react-router-dom';
import FourthView from '../fourthview/fourthview.component';
import {Bootstrap, Grid, Row, Col, Button, Image, Modal, Popover} from 'react-bootstrap';
import traineeship from './traineeship.api';
import Header from '../header/header.component';
import InfiniteScroll from 'react-infinite-scroller';
require('./traineeship.style.scss');
class Traineeship extends React.Component {
constructor(props) {
super(props);
this.state = {
companies: [],
page: 0,
resetResult: false,
};
}
componentDidMount() {
this.fetchCompanies(this.state.page);
}
fetchCompanies(page){
traineeship.getAll(page).then(response => {
if (response.data) {
this.setState({companies: this.state.companies.concat(response.data._embedded.companies)});
} else {
console.log(response);
}
});
}
render() {
return (
<div className={"wrapperDiv"}>
{JSON.stringify(this.props.rootState)}
<div className={"flexDivCol"}>
<div id="header">
<Header/>
</div>
<div id="result">
<div className={"search"}>
<h2>Harjoittelupaikkoja</h2>
<p className={"secondaryColor"}>{this.state.companies.length} paikkaa löydetty</p>
</div>
<div className={"filters"}>
<h5 style={{marginTop: '30px', marginBottom: '10px'}} className={"primaryColor"}>
Hakukriteerit</h5>
<div className={"filter"}>Ravintola- ja cateringala</div>
<div className={"filter"}>Tarjoilija</div>
<div className={"filter"}>Kaikki</div>
</div>
<div className={"searchResults"}>
<h5 style={{marginTop: '30px', marginBottom: '10px'}} className={"primaryColor"}>
Hakutulokset</h5>
<InfiniteScroll
pageStart={0}
loadMore={() => this.fetchCompanies.bind(this)}
hasMore={true || false}
loader={<div className="loader" key={0}>Loading ...</div>}
useWindow={false}
>
{
this.state.companies.map((traineeship, key) => (
<div id={"item"} key={key}>
<div className={"companyInfo"}>
<div className={"heading"}>
<div id={"companyDiv"}>
<p style={{
fontSize: '18px',
lineHeight: '18px'
}}>{traineeship.name}</p>
</div>
{
traineeship.video === null
? ''
:
<div id={"videoDiv"}>
<div className={"youtubeBox center"}>
<div id={"youtubeIcon"}>
<a className={"primaryColor"}
href={traineeship.mediaUrl}>
<span style={{marginRight: '3px'}}><Image
src="http://www.stickpng.com/assets/images/580b57fcd9996e24bc43c545.png"
style={{
width: '24px',
height: '17px'
}}/></span>
<span> <p style={{
fontSize: '13px',
lineHeight: '18px',
margin: 0,
display: 'inline-block'
}}>Esittely</p></span>
</a>
</div>
<div id={"txtVideo"}>
</div>
</div>
</div>
}
</div>
<div className={"location"}>
<div id={"locationIcon"}>
<Image src="assets/img/icLocation.png" style={{marginTop: '-7px'}}/>
</div>
<div id={"address"}>
<a href={"https://www.google.com/maps/search/?api=1&query=" + encodeURI("Fredrikinkatu 4, Helsinki")}>
<p className={"primaryColor"}
style={{fontSize: '13px'}}>{traineeship.city}(show in
map)</p>
</a>
</div>
</div>
<div className={"companyDescription"}>
<p className={"secondaryColor"} style={{
fontSize: '14px',
lineHeight: '20px'
}}>{traineeship.description}</p>
</div>
<div className={"companyContacts"} style={{marginTop: '20px'}}>
<p className={"contactInfo"}>URL: {traineeship.website}</p>
<p className={"contactInfo"}>Email: {traineeship.email}</p>
<p className={"contactInfo"}>Puh: {traineeship.phonenumber}</p>
<p className={"contactInfo"}>Contact: {traineeship.contact}</p>
</div>
</div>
</div>
))
}
</InfiniteScroll>
</div>
</div>
</div>
</div>
);
}
}
export default Traineeship;
So basically it just shows only first five article, page is not increasing!
#Mizlul: Does fetchCompanies invoked every time scroll happens ? Can you please check that ? Also you are mutating the state here, this.state.companies.concat(response.data._embedded.companies)..
Can you update it to ,
const companies = Array.from(this.state.companies);
this.setState({ companies: companies.concat(response.data._embedded.companies) });
I'm not sure about that .bind(this). Try making your method an arrow function (to implicitly bind the this context):
constructor() {
// ...
this.fetchCompanies = this.fetchCompanies.bind(this);
}
fetchCompanies(page) {
return traineeship.getAll(page).then(response => {
if (response.data) {
this.setState({
companies: this.state.companies.concat(
response.data._embedded.companies
)
});
} else {
console.log(response);
}
});
}
// In your render's return:
<InfiniteScroll
pageStart={0}
loadMore={() => this.fetchCompanies(this.state.page)}
hasMore={true || false}
loader={
<div className="loader" key={0}>
Loading ...
</div>
}
useWindow={false}
>;

How to prevent react component click event bubble to document?

How to prevent react component click event from bubble up to document ?
I can sure that there must be something was wrong with it!
So, may be I should help myself fix it!
I just have a box component which has a click event listener, and there are some link components in that box which are effected by a document click event. How can I remove this document click event?
Can someone do me a favor?
More details info can be found in following links!
Here is the code link : https://github.com/ant-design/ant-design/issues/6576
Click has no effect, it should link to item3!
Remove document's click event
After that, it works!
What's wrong with this?
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import logo from './logo.svg';
import './App.css';
// import SideBox from './SideBox.js';
// import ContentBox from './ContentBox.js';
/*import SidebarExample from './test.js';*/
// import ReactDOMServer from 'react-dom/server';
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom';
import Item1 from './components/Item1.js';
import Item2 from './components/Item2.js';
import Item3 from './components/Item3.js';
import {Menu, Icon} from 'antd';
import 'antd/dist/antd.css';
const SubMenu = Menu.SubMenu;
const element = <h1>Hello, world</h1>;
const elements = () => {
return(
<h1>Hello, world</h1>
);
};
const routes = [
{
path: '/',
exact: true,
sidebar: () => <div>item1</div>,
main: () => <div><Item1 /></div>
},
{
path: '/item2',
sidebar: () => <div>item2</div>,
main: () => <div><Item2 /></div>
},
{
path: '/item3',
sidebar: () => <div>item3</div>,
main: () => <div><Item3 /></div>
}
]
class App extends Component {
constructor(props) {
super(props);
this.state = {
message: props.message,
styles: props.styles,
Any: props.any,
width: props.width,
theme: 'dark',
current: '1'
};
this.handleMenuClick = this.handleMenuClick.bind(this);
this.handleClick = this.handleClick.bind(this);
};
handleClick(e) {
console.log('click ', e);
this.setState({
current: e.key,
});
};
// ES7 property initializer syntax
handleMenuClick = (e) => {
e.preventDefault();
// e.stopPropagation();
// e.nativeEvent.stopImmediatePropagation();
console.log('this is:', this);
console.log("clicked === \n", e);
if(this.state.styles === "App-SideBox-init"){
this.setState({
message: "e.key",
styles: "App-SideBox-New",
width: "width: 40px;"
});
}
if(this.state.styles === "App-SideBox-New"){
this.setState({
message: "Hello!",
styles: "App-SideBox-init",
width: "width: 300px;"
});
}
console.log("this.state.message === ", this.state.message);
console.log("this.state.styles === ", this.state.styles);
};
componentDidMount() {
/*window.addEventListener('scroll', this.onScroll.bind(this), false);*/
// window.removeEventListener('click', this.handleMenuClick.bind(this), false);
// window.removeEventListener('click', this.handleClick.bind(this), false);
};
render() {
return (
<div className="App">
<div className="App-header">
<img id="img" src={logo} className="App-logo" alt="logo" style={this.props.width}/>
<h2>Welcome to React</h2>
</div>
<div className="App-SideBox">
<div className={this.state.styles}>
<Router>
<div>
<div style={{ display: 'flex' }}>
<div style={{
padding: '10px',
width: '30%',
background: '#f0f0f0'
}}>
<div className="SideBox-body" style={{ display: 'flex' }}>
<Menu
theme={this.state.theme}
onClick={this.handleClick}
style={{ width: 240 }}
defaultOpenKeys={['sub1']}
selectedKeys={[this.state.current]}
mode="inline"
>
<SubMenu
key="sub1"
title={
<span>
<Icon type="mail" />
<span>Navigation One</span>
</span>
}
>
<Menu.Item key="1">
<Link to="/"> item1</Link>
</Menu.Item>
<Menu.Item key="2">
<Link to="/item2">item2</Link>
</Menu.Item>
<Menu.Item key="3">
<Link to="/item3">item3</Link>
</Menu.Item>
</SubMenu>
</Menu>
</div>
</div>
</div>
</div>
</Router>
</div>
{/*onClick={this.handleMenuClick}*/}
<div onClick={this.handleMenuClick} className="App-SideBox-btn">
<span>icon</span>
</div>
</div>
<div className="App-body">
<Router>
<div>
<div>
<div style={{ flex: 1, padding: '10px' }}>
{
routes.map((route, index) => (
<Route
key={index}
path={route.path}
exact={route.exact}
component={route.main}
/>
))
}
</div>
</div>
</div>
</Router>
</div>
</div>
);
}
};
App.defaultProps = {
message: 'Hello!',
styles: 'App-SideBox-init'
};
App.propTypes = {
message: PropTypes.string.isRequired,
styles: PropTypes.string.isRequired,
width: PropTypes.string
};
export default App;
Just make all event handlers on the parent component, and then pass them to children by using props!

Categories