Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function is working on main page but stops on second pages

I am trying to make a website with ReactJS. In my website I have a slice button on the main page;

When you click the slice button, each side shows a different image.

I add links to the Menu bar as well for the slice button (I am going to call Left - Right) so when you click the link, the first go to the part of the main page then it moves the slice button and shows the image.

I do not have any problem with the links when I am on the main page but the problem is; I am using same Menu bar for all pages and when I click the Left and the Right right links in the Menu on a different page it stops.

The links open the main page but stay the beginning of the main page.

UPDATE 2: Although the problem is not with the Toggle button but I want to add the toggle function in the main page that you can see all.

Note: I remove toggle button but links are not working (Right I cannot see the buttons when I remove the function but when I click the link in the menu, the page does not link to exact part of the button placed in the main page so still I have the same problem .)

Here is my ChangeViewButtonClick function in main;

import React, { Component } from "react";


class Main extends React.Component{

  constructor(props) {
    super(props);
    this.state = {
      view: "Left"
    };
    this.ChangeViewButtonClick = this.ChangeViewButtonClick.bind(this);
    this.ChangeViewToggle = this.ChangeViewToggle.bind(this);
  }

   togglePopup() {
    this.setState({
      showPopup: !this.state.showPopup
    });
  }

  ChangeViewToggle() {
    if (this.refs.toggle.state.checked === true) {
      this.setState({ view: "Left" });
      this.refs.toggle.state.checked = false
    } else  {
      this.setState({ view: "Right" });
      this.refs.toggle.state.checked = true
    }
  }
  ChangeViewButtonClick(view) {
    if (view === "Left") {
      this.setState({ view: "Left" });
      this.refs.toggle.state.checked = true
    } else if (view === "Right") {
      this.setState({ view: "Right" });
      this.refs.toggle.state.checked = false
    }
  }

  render(){
    return(
      <div>
        <h1> 
           <footer className="togglefooter">
            <label>
                  &nbsp;
                  <span style={{ color: "black", fontWeight: "normal" }}>
                   Left
                    &nbsp;
                  </span>
                  <Toggle
                    id="toggle"
                    ref="toggle"
                    defaultChecked={this.state.view}
                    icons={false}
                    onChange={() => this.ChangeViewToggle()}
                  />
                  <span style={{ color: "black", fontWeight: "normal" }}>
                    &nbsp;
                    Right
                  </span>
                </label>
              </footer>
        </h1>
      </div>
    );
  }
}

and this is my Menu Page ;

import React from 'react';
import { Collapse, Navbar, NavbarToggler, NavbarBrand, NavLink} from 'reactstrap';
import { HashLink as Link } from 'react-router-hash-link';


class Menu extends React.Component {  
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      isOpen: false
    };
  }

  toggle() {
    this.setState({
      isOpen: !this.state.isOpen
    });
  }

  render() {
    return(
      <Navbar light expand="md">
        <NavbarToggler onClick={this.toggle} />
        <Collapse isOpen={this.state.isOpen} navbar>
          <nav className="nav">
            <ul className="nav__menu">
              <li className="nav__menu-item">
                <NavLink to="#" tag= {Link} >
                  Images
                </NavLink>
                <Image_SubMenu ChangeViewButtonClick{this.props.ChangeViewButtonClick}/>
              </li>
              <li className="nav__menu-item">
                <NavLink tag={Link} to="/main#something">
                  Something
                </NavLink>
              </li>
            </ul>
          </nav>
        </Collapse>
      </Navbar>
    );
  }
}

class Image_SubMenu extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <ul className="nav__submenu">
        <li className="nav__submenu-item ">
          <NavLink to="/main#map" tag={Link} onClick={evt => this.props.ChangeViewButtonClick("Left")}>
            Left Image
          </NavLink> 
        </li>
        <li className="nav__submenu-item ">
          <NavLink to="/main#map" tag={Link} onClick={evt => this.props.ChangeViewButtonClick("Right")} >
            Right Image
          </NavLink>
        </li>
      </ul>
    )
  }
}

export default Menu;

How can I fix the link that if I click on the link anywhere on the website then shows me Left or Right images

I found a few articles about delegated events unfortunately I could not figure out.

Thanks in advance

Note that this is only part of the code and just paste the part that you need so if I miss something please tell me so can be a few typos.

Update: I would like to add my other two pages here because the information that I shared might not be enough.

I am trying to click links that are inside the Menu and I have the problem

About page:

import React from "react";
import ReactGA from 'react-ga'
//Import components
import Footer from "./components/Footer.js";
import Menu from "./components/Menu.js";

function About(props) {  
  return ( 
    <div>
      <div className="bgded overlay">
        {/* Menu Component */}
        <Menu ChangeViewButtonClick={props.ChangeViewButtonClick}/>
      </div>
      {/* Start of Project Aims */}
      <a id ="aims" />
      <div className="wrapper row3">
        <main className="hoc container clear" style={{ paddingTop: "30px" }}>
          <article className="one_third first" style={{ width: "100%" }}>
            <h4 className="font-x2 font-x3">
              Something about project
            </h4>
            <p>Something is here too..</p>
          </article>
          <div className="clear" />
        </main>
      </div>
      {/* Footer Component */}
      <Footer />
    </div>
  );
}

export default About;

Report Page:

import React, { Component } from "react";
import ReactGA from 'react-ga';
import ReactDependentScript from 'react-dependent-script';
import Footer from "./components/Footer.js";
import Menu from "./components/Menu.js"
//Import PNG Image
//import { domain } from "./config.json";
import GraphHover from "./components/GraphHover.js";

class report extends Component {
  constructor(props) {
    super(props);
    this.state = {
      displayGraph: "none",
      graphTitle: null,
      graphPreview: null,
      graphHoverLeft: "0",
      previewImages: null,
    };
    this._onMouseLeave = this._onMouseLeave.bind(this);
    this.DisplayHoverGraph = this.DisplayHoverGraph.bind(this);
  }

  _onMouseLeave(evt) {
    this.setState({ displayGraph: "none" });
  }

  DisplayHoverGraph(input, image, evt) {
    //Disable hover effect if on a mobile device
    if (!this.props.isMobileDevice) {
      this.setState({
        graphTitle: input,
        previewImage: image,
        displayGraph: "inline"
      });

      if (evt.clientX < window.screen.width / 2) {
        this.setState({ graphHoverLeft: "1200px" });
      } else {
        this.setState({ graphHoverLeft: "0" });
      }
    }
  }

  componentDidMount() {
    console.log(window.test)
  }

  render() {
    return (
      <div>
        <GraphHover
          position="fixed"
          top={this.state.graphHoverTop}
          left={this.state.graphHoverLeft}
          displayPreview={true}
          display={this.state.displayGraph}
          graphTitle={this.state.graphTitle}
          previewImage={this.state.previewImage}
          graphHeadingSize={this.state.graphHeadingSize}
          width={this.state.graphHoverWidth}
          height={this.state.graphHoverHeight}
        />
        <div className="bgded overlay">
          {/* Menu */}
          <Menu ChangeViewButtonClick={this.props.ChangeViewButtonClick} />
        </div>
        <div className="wrapper row3">
          <a id="sumary" />
          <main className="hoc container clear" style={{ paddingTop: "30px" }}>
            <div className="clear" />
          </main>
        </div>
        <Footer />
      </div>
    );
  }
}

export default report;
like image 267
Axis Avatar asked Jan 15 '19 01:01

Axis


People also ask

How do you call a function on page refresh in react JS?

import React from 'react'; function App() { function refreshPage() { window. location. reload(false); } return ( <div> <button onClick={refreshPage}>Click to reload!

How do I limit a JavaScript function to run only once?

var something = (function() { var executed = false; return function(value) { // if an argument is not present then if(arguments. length == 0) { if (! executed) { executed = true; //Do stuff here only once unless reset console.

What is use of in JS?

The JavaScript in operator is used to check if a specified property exists in an object or in its inherited properties (in other words, its prototype chain). The in operator returns true if the specified property exists. Anatomy of a simple JavaScript object.

How do you stop a function from working in JavaScript?

To stop the execution of a function in JavaScript, use the clearTimeout() method.


1 Answers

You need to pass the prop ChangeViewButtonClick via the parent Class (In your case, Main ) to the child class (In your case the class About or class Report ).

So your structure would be like this -
Main
----About
----Report.

The reason I am mentioning that about and report will be child of your Main class because they are accessing the prop function like this <Menu ChangeViewButtonClick={this.props.ChangeViewButtonClick} /> where this.props.ChangeViewButtonClick should be made available to report and about page.

Note: You might need to add a navigation logic to load the respective pages. I will give a simple snippet below

import React, { Component } from "react";
import Menu from './Menu'
import report from "./report"
import about from "./about"

class Main extends React.Component{

constructor(props) {
    super(props);
    this.state = {
      view: "Left"
   };
 this.ChangeViewButtonClick = this.ChangeViewButtonClick.bind(this);
 }

    ChangeViewButtonClick(view) {
    if (view === "Left") {
      this.setState({ view: "Left" });
      this.refs.toggle.state.checked = true
    } else if (view === "Right") {
      this.setState({ view: "Right" });
      this.refs.toggle.state.checked = false
    }
  }

render(){
return(
    <div>
        <h1>Main Page is Here </h1>
        // Some navigation logic between the pages below
        <report onChangeViewButtonClick={this.ChangeViewButtonClick} />
        <about onChangeViewButtonClick={this.ChangeViewButtonClick} />

    </div>
  );
 }
}
like image 108
Aakash Gandhi Avatar answered Oct 03 '22 10:10

Aakash Gandhi