0

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 ?

4
  • on click in textfield or when clicked on AppComponent? Commented Apr 2, 2017 at 14:07
  • is the Sidebar child of the App component? Commented 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 event Commented Apr 2, 2017 at 14:10
  • sidebar is not a child component Commented Apr 2, 2017 at 14:11

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

3 Comments

I don't want to use onchange event on input box
Please explain, why?
Worked work me ... What if I want to get data from multiple fields like username / password?
0

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

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
look into next answer, here it is

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.