简体   繁体   中英

how to pass function variable from one file to another in react

I'm doing a quiz application where I have the final score in a function in app.js, now I want to draw a graph based on user result(show in bar graph like 6 right,4 wrongsomething like that), so I wrote a function to plot the graph in another file(chart.js) using chart.js 2. the thing is I'm not able to pass the final score from app.js to chart.js. at the end I want to show that graph also. note:I have used line chart for this, just to check whether my value is passing or not. App.js

 export default function App() { return ( <div className='app'> {showScore ? ( <div className='score-section'> You scored {score} out of {questions.length} <LineChart/> </div> ) : ( ) ) }

chart.js

import React from 'react';
import {Line} from 'react-chartjs-2'
import App from '../App'
//import {score} from '../App'
//import {myExport} from '../App'
 
export default function LineChart()
{
    //console.log(App.score);
    
    

    const data = {
        
        
        labels:['jan','feb','march','april'],
        datasets:
        [
            {
                
                label:"sales",
                data:[10,7,9]

            }
        ]


        
    }
return( 
    
<div>

<Line data= {data}/>


</div>
    
    )
}

Just pass your score and question count as a prop to your LineChart component.

{showScore ? (
                <div className='score-section'>
                    You scored {score} out of {questions.length}

                    <LineChart
                        score={score}
                        question_count={questions.length}
                    />
                    
                </div>
            ) :

Then in your LineChart component, you can access them as

this.props.score
this.props.question_count

Yannick is right. i have to pass it as a prop. i made a mistake, in app.js LineChart function I passed it like Linechart(score), it should be Line chart({score}). corrected code is.

 //App.js <LineChart score={score} total={questions.length} />

 //Chart.js export default function LineChart({score,total}) and you can use score and total anywhere in you're function body.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM