Search code examples
javascriptarraysreactjscomponentsvar

How do I pass the value of a variable through the components in react?


That's my App.js

import React, { Component } from 'react'
import { BrowserRouter as Router, Route, Link} from "react-router-dom";

import Particles from './components/particles'
import Title from './components/start'
import Explain from "./components/explain"
import "./App.css"
import Test from "./components/test"
import Test1 from "./components/IntLin/test1"
import Test2 from "./components/IntLin/test2"
import Test3 from "./components/IntLin/test3"

export default class App extends Component{

render(){
  return (
    <div>
      <Router>
        <div className="start">
          <Particles/>
          <Route exact path="/inicio" render={() => {
          return <div className="titulo">
          <Title}/>
          </div>
          }}>
          </Route>
        </div>
          <Route exact path="/explain" render={() => {                    
            return <div className="explain">
              <Explain}/>
            </div>
            }}>
          </Route>
          <Route exact path="/test" render={() => {
            return <div className="test">
              <Test/>
            </div>
          }}>
          </Route>
           <Route exact path="/test1" render={() => {
              return <div className="test1">
                <Test1/>
              </div>
            }}>
            </Route>
            <Route exact path="/test2" render={() => {
              return <div className="test2">
                <Test2/>
              </div>
            }}>
            </Route>
            <Route exact path="/test3" render={() => {
              return <div className="test3">
                <Test3/>
              </div>
            }}>
            </Route>
        </Router>
      </div>
      );
  };

}

So, basically I want to set a numeric variable in app.js, then when I go to the 'Test' component I can find the variable and add +1 and then the next component 'Test1' can subtract -1 and so on through all the components until you reach the final component where you will get how much was the final variable.


Solution

  • you can use both passing props or Context but what you really want to do is to pass a two or three things.

    1. variable
    2. incremeant funciton
    3. decrement function

    or you can combine number 2 and 3 :)

    here is the example: https://codesandbox.io/s/74qzy90m3x