Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass data from one React component to another?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
  )

>Solution :

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 🙁

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading