I'm new to react so please bear with me.
What I want to do:
Essentially pass data from Child Component, to Parent Component, back to another Child Component.
<ParentComponent>
<ChildComponent1>
<ChildComponent2>
</ParentComponent>
Child Component1 has a form.
When form is submitted...
1.) state should be updated with form's content.
2.) state data should pass onto parent component.
3.) Parent Component should pass the data onto ChildComponent2
4.) ChildComponent2 now has access to data from ChildComponent1, and can manipulate said data.
Here is my code.
import styles from './Body.module.css';
import {LeftPortion} from './LeftPortion/LeftPortion.js';
import RightPortion from './RightPortion/RightPortion.js';
class Body extends Component {
constructor(props){
super(props)
this.state={
teamOne: '',
teamTwo: ''
};
this.updateBetInfo = this.updateBetInfo.bind(this);
}
updateBetInfo(firstTeam, secondTeam){
this.setState({teamOne: firstTeam, teamTwo: secondTeam})
}
render(){
return(
<div className={styles.container}>
<LeftPortion updateParent={this.updateBetInfo}/>
<RightPortion/>
</div>
);
}
}
export default Body;
import styles from './LeftPortion.module.css';
export class LeftPortion extends Component{
constructor(props){
super(props)
this.state={
teamOne:'',
teamTwo:''
}
this.onChange= this.onChange.bind(this);
this.onSubmitForm= this.onSubmitForm.bind(this);
}
onChange(event){
this.setState({[event.target.name]: event.target.value})
}
onSubmitForm(teamOne, teamTwo){
var teamOne = this.state.teamOne;
var teamTwo = this.state.teamTwo;
this.props.updateParent(teamOne,teamTwo)
}
render(){
return(
<div className={styles.container}>
<h4>Enter bet info here:</h4>
<h4>-------------------</h4>
<h4>Straight bet</h4>
<div className={styles.teamEntry}>
<form>
<label>
Team 1:
<input type="text" name="teamOne"onChange={this.onChange}/>
</label>
<br/>
<label>
Team 2:
<input type="text" name="teamTwo" onChange={this.onChange}/>
</label>
<br/>
<input type="submit" value="Submit" onClick={this.onSubmitForm}/>
</form>
<br/>
<div className={styles.betType}>
<form>
<label>
Bet:
<select>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='X'>X</option>
</select>
</label>
<input type="submit" value="Submit"/>
</form>
</div>
</div>
</div>
);
}
}
Basically what I'm stuck on is I need the state in to update to the teamOne and teamTwo entered in the form from the child component, when the form is submitted.
It appears you are not assigning any props to the second component you want the state to update? Is your parent component's state update being executed? If so, assign a state value to child component 2, and it should be working fine. Right now, React won't re-render anything as there are no children with props or state impacted by the update.
<RightPortion/>
This component should have a state value to reflect the update in the parent.
<RightPortion teamOne={this.state.teamOne} />