How can I pass a prop attribute in one component to other component ? (React Js) I want the Statistic components to be displayed only after clicking any of the 3 buttons that I've created. When I tried to move the Statistic components to History component(in the second return, below 'button press history: ...'), now I am facing the problem of variables not defined(good, neutral, bad, all2 are not defined). How can I use the variables that I've defined in one component so that it can be used in other component ? Here's my code,
App.js
import { useState } from 'react'
const History = (props) => {
if (props.allClick.length === 0) {
return (
<div>
the app is used by pressing the buttons
</div>
)
}
return (
<div>
button press history: {props.allClick.join(' ')}
</div>
)
}
const Button = (props) => {
return (
<div>
<button onClick={props.handleClick}> {props.text} </button>
</div>
)
}
const Statistic = (props) => {
return (
<div>
<p>{props.title} {props.type} </p>
</div>
)
}
const App = () => {
// save clicks of each button to its own state
const [good, setGood] = useState(0)
const [neutral, setNeutral] = useState(0)
const [bad, setBad] = useState(0)
const [allClick, setClick] = useState([])
const inlineButton = {
display: 'inline-flex',
gap: '10px'
}
const goodClick = () => {
setClick(allClick.concat('G'))
setGood(good + 1)
}
const neutralClick = () => {
setClick(allClick.concat('N'))
setNeutral(neutral + 1)
}
const badClick = () => {
setClick(allClick.concat('B'))
setBad(bad + 1)
}
const all2 = good+neutral+bad
return (
<div>
<h1> give feedback </h1>
<div style={inlineButton}>
<Button handleClick={goodClick} text="good"/>
<Button handleClick={neutralClick} text="neutral"/>
<Button handleClick={badClick} text="bad" />
</div>
<h1> statistics </h1>
<History allClick={allClick} />
<Statistic title="good" type={good}/>
<Statistic title="neutral" type={neutral}/>
<Statistic title="bad" type={bad}/>
<Statistic title="all" type={all2}/>
<Statistic title="positive" type={good/all2 * 100} />
</div>
)
}
export default App
index.js
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
ReactDOM.createRoot(document.getElementById('root')).render(<App />)
Problem solved, in the App.js,
<History allClick={allClick} good={good} neutral={neutral} bad={bad} />
and in the History component,
const History = (props) => {
if (props.allClick.length === 0) {
return <div>the app is used by pressing the buttons</div>;
}
const all2 = props.good + props.neutral + props.bad;
return (
<>
<div>button press history: {props.allClick.join(" ")}</div>
<Statistic title="good" type={props.good} />
<Statistic title="neutral" type={props.neutral} />
<Statistic title="bad" type={props.bad} />
<Statistic title="all" type={all2} />
<Statistic title="positive" type={(props.good / all2) * 100} />
</>
);
};
Please sign in or create an account to participate in this conversation.