skip to Main Content

Being very new to React, I am having a hard time in passing the data across to other components from the parent component<App.js>. I am sharing the code below for reference. My goal is to pass the variable stocksName to other components such as Stocks.js where currently it is not being recognized. Any help would be highly appreciated.

App.js

import React, { useState, useEffect } from 'react'
import Select from 'react-dropdown-select';
import axios from 'axios';
import './App.css'
import StocksView from './components/Stocks'

function App() {

  const [data, setData] = useState([]);
  const [stocksName, setStocksName] = useState([]);
  const [selectvalue, setselectvalue] = useState([]);
  const [message, setMessage] = useState("");

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(selectvalue);
    axios.post("./getStocks", selectvalue)
      .then((response) => {
        console.log(response);
        const nodeData = JSON.parse(response.data.nodeData);
        setStocksName(nodeData.STOCKS_NAME);
      }).catch((error) => {
        console.log(error);
      });
  };

  useEffect(() => {
    fetch("/listPartitions")
      .then((response) => response.json())
      .then((partition) => {
        const parsed = JSON.parse(partition.nodePartition);
        const partitions = Object.entries(parsed).map(([key, value]) => ({
          label: value,
          value: key
        }));

        // put the partitions data in the state
        setData(partitions);
        console.log(parsed, partitions);
      });
  }, []);

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <Select
          name="select"
          options={data}
          multi
          onChange={(selected) => setselectvalue(selected.map((item) => item.label))
          }
        />
        <button type="submit">Submit</button>
        <div className="message">{message ? <p>{message}</p> : null}</div>
      </form>
      <div>
        <StocksView/>
      </div>
    </div>

  )
}

export default App;

Stocks.js

import React from 'react'
import Graph from 'react-vis-network-graph'

export default function StocksView() {
    const stocks = {
        nodes: [
            {stocksName}
        ]
    }
    
     return (
    <div className='container'>
        <Stocks 
            stocks={stocks}
        />
    </div>
  )

2

Answers


  1. To pass the stocksName variable from the App component to the StocksView component, you can simply pass it as a prop.

    Another way to achieve this is by creating a global store, which is a more advanced method suitable for managing a lot of state. But, as of now you can proceed with concept of props (Check here)

    Here, is how you can do this with props.

    App.js:

    import React, { useState, useEffect } from 'react'
    import Select from 'react-dropdown-select';
    import axios from 'axios';
    import './App.css'
    import StocksView from './components/Stocks'
    
    function App() {
    
      const [data, setData] = useState([]);
      const [stocksName, setStocksName] = useState([]);
      const [selectvalue, setSelectValue] = useState([]);
      const [message, setMessage] = useState("");
    
      const handleSubmit = (event) => {
        event.preventDefault();
        console.log(selectvalue);
        axios.post("./getStocks", selectvalue)
          .then((response) => {
            console.log(response);
            const nodeData = JSON.parse(response.data.nodeData);
            setStocksName(nodeData.STOCKS_NAME);
          }).catch((error) => {
            console.log(error);
          });
      };
    
      useEffect(() => {
        fetch("/listPartitions")
          .then((response) => response.json())
          .then((partition) => {
            const parsed = JSON.parse(partition.nodePartition);
            const partitions = Object.entries(parsed).map(([key, value]) => ({
              label: value,
              value: key
            }));
    
            // put the partitions data in the state
            setData(partitions);
            console.log(parsed, partitions);
          });
      }, []);
    
      return (
        <div>
          <form onSubmit={handleSubmit}>
            <Select
              name="select"
              options={data}
              multi
              onChange={(selected) => setSelectValue(selected.map((item) => item.label))
              }
            />
            <button type="submit">Submit</button>
            <div className="message">{message ? <p>{message}</p> : null}</div>
          </form>
          <div>
            <StocksView stocksName={stocksName}/> {/* Passing stocksName as prop */}
          </div>
        </div>
      )
    }
    
    export default App;
    

    Stocks.js:

    import React from 'react'
    import Graph from 'react-vis-network-graph'
    
    export default function StocksView({ stocksName }) { // Accepting stocksName as a prop
        const stocks = {
            nodes: [
                {stocksName}
            ]
        }
        
         return (
        <div className='container'>
            <Graph // I suppose you meant to use Graph here instead of Stocks
                stocks={stocks}
            />
        </div>
      )
    }
    

    Now, stocksName from the App component will be passed to the StocksView component as a prop and can be accessed within StocksView as stocksName.

    Let me know, if you’ve any questions 🙁

    Login or Signup to reply.
  2. You can use Context.Provider

    I have the same problem a few days ago

    This helped me so much https://es.react.dev/reference/react/createContext

    With Context you can use your variables in all your components

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search