Reputation: 12729
could you please tell me how to move one component to another component on button click in react ?
I get the react-router.js
from cdn .I don't know how to use this js ..I want to show second component on button click of
first component` here is my code
http://codepen.io/anon/pen/jVoZjW?editors=1010
class Abc extends React.Component {
handle(){
alert('move to second component')
}
render (){
return (<div><h1>second</h1><button onClick={this.handle}>move to second page</button></div>);
}
}
class Pqr extends React.Component {
render (){
return (<div><h1>second</h1><button>click</button></div>)
}
}
class Sqr extends React.Component {
render (){
return <h1>third</h1>
}
}
ReactDOM.render(<Abc/>,document.getElementById('root'));
Upvotes: 1
Views: 10500
Reputation: 566
There is many ways this can be accomplished, all of which have there place. This is but one of many methods:
I left an alternitive to this answer aswell this answer on the codepen: http://codepen.io/dirtyredz/pen/gLJeWY
class Abc extends React.Component {
constructor(){
super();
this.state={first: true};
}
handle(){
alert('move to second component')
this.setState({first: false})
}
render (){
return (
<div>
<button onClick={this.handle.bind(this)}>move to second page</button>
{this.state.first == true && <Pqr/>}
{this.state.first == false && <Sqr/>}
</div>
);
}
}
class Pqr extends React.Component {
render (){
return (<div><h1>First</h1></div>)
}
}
class Sqr extends React.Component {
render (){
return <h1>Second</h1>
}
}
ReactDOM.render(<Abc/>,document.getElementById('root'));
This is a quick example, like i said earlier others may be better but this works as expected.
Upvotes: 2