Im working in react for the first time and ive got an app that takes two numbers from the user and has them select an operator. i want to take that info and display it in a sub component but i can get it for the life of me.
<script type="text/babel">
const main = ReactDOM.createRoot(document.getElementById('root'));
function Inputs(props) {
const[val1, setVal1] = React.useState(props.num1);
const[val2, setVal2] = React.useState(props.num2);
let symbols = ['+', '-', 'x', '÷'];
const[sym, setSym] = React.useState(props.opp);
const getVal = () => {
setVal1(first.value);
setVal2(second.value);
}
const getSym = (num) => {
setSym(symbols[num])
}
return(
<div>
<input id= 'first'></input>
<input id= 'second'></input>
<p>{val1}</p>
<p>{val2}</p>
<p>{sym}</p>
<button id= 'get' onClick ={getVal}>get</button>
<button id= 'add' onClick ={() => getSym(0)}>+</button>
<button id= 'subtract' onClick ={() => getSym(1)}>-</button>
<button id= 'multiply' onClick ={() => getSym(2)}>x</button>
<button id= 'divide' onClick ={() => getSym(3)}>÷</button>
<SubComponent />
</div>
)
}
class SubComponent extends React.Component {
render() {
return(
<p>SubComponent{this.props.value}</p>
)
}
}
main.render(<Inputs />);
Ive tried using props and a few other things but no dice
3
Answers
I can see you are not passing any props while calling the "SubComponent" but trying to access like :
Instead you should be passing the props to your "SubComponent" like <SubComponent value={{val1, val2, sym}} /> and then try accessing them like
you can try redux , redux is a powerful Library for sharing data one component to all completes like child to parent, parent to childs, child to child etc
Sure, here’s a shorter and more concise answer:
To pass data from your
Inputs
component to theSubComponent
, you need to pass props correctly. Update your code like this:This should fix the issue with passing data to your sub-component.