I have two components one is app component and other one is sidebar component i have been using input field in side bar and i want to get the value of that input field in my app component on click how this could be possible ?
-
on click in textfield or when clicked on AppComponent?mfahadi– mfahadi2017-04-02 14:07:11 +00:00Commented Apr 2, 2017 at 14:07
-
is the Sidebar child of the App component?Tharaka Wijebandara– Tharaka Wijebandara2017-04-02 14:09:20 +00:00Commented Apr 2, 2017 at 14:09
-
i have small form in sidebar component want to get the value of input field which is in that form in the app component on click event and i dont want you use on change eventZohaib Ahmad– Zohaib Ahmad2017-04-02 14:10:47 +00:00Commented Apr 2, 2017 at 14:10
-
sidebar is not a child componentZohaib Ahmad– Zohaib Ahmad2017-04-02 14:11:03 +00:00Commented Apr 2, 2017 at 14:11
Add a comment
|
2 Answers
You can try lifting the state up.
Create a new component that will contain your two components. In that new component, create a function that you will pass as props inside the sidebar component.
class ContainerComponent extends React.Component {
constructor() {
super();
this.state = {
valueThatNeedsToBeShared: ''
}
}
handleChange(e) {
this.setState({valueThatNeedsToBeShared: e.target.value})
}
render() {
return (
<div>
<AppComponent value={this.state.valueThatNeedsToBeShared} />
<SidebarComponent handleChange={this.handleClick.bind(this)} value={this.state.valueThatNeedsToBeShared} />
</div>
)
}
}
const SidebarComponent = ({handleChange, value}) => <aside>
<input value={value} onChange={handleChange} />
</aside>
const AppComponent = ({value}) => <div>
value from sidebar: {value}
</div>
3 Comments
Zohaib Ahmad
I don't want to use onchange event on input box
AlexeyKuznetsov
Please explain, why?
Omer
Worked work me ... What if I want to get data from multiple fields like username / password?
In pure react it is possible by adding callback from one component and use it into parent component to change their state and then send input value from parent's state to props of your second component
2 Comments
Zohaib Ahmad
Do you have any example ? . i did use the slight different way define funtion in app component and triggered in sidebar component in app component i could get this via refs or documetn.getelment by id by puting id on the input field in input box which is in sidebar component
AlexeyKuznetsov
look into next answer, here it is