Afnan Nazir Afnan Nazir - 20 days ago 6
React JSX Question

React component appears and disappears instantly

I have been given a task where i have to show different components in a div depending upon click on menu. Previously those were shown in tabs(and they were working fine) now i have to remove tabs and show menus instead.
My code is this

handleClick: function (name) {
ReactDOM.unmountComponentAtNode(document.getElementById('main_data'));
if (name == 'projects') {
ReactDOM.render(<ListProjects parentThis = {this} />, document.getElementById('main_data'))
}
else if (name == 'profile') {
ReactDOM.render(<div className="inner clearfix">
<Avatar parentThis = {this}/>
</div>,
document.getElementById('main_data'))
}

render: function () {
return (
<div className="row">
<div className="col-sm-12">
<div className="user-menu">
<ul className="dropdown clearfix boxed">
<li key="1"><a href="#" onClick={()=>this.handleClick('projects')}><span>Projects</span></a></li>
<li key="2"><a href="#" onClick={()=>this.handleClick('profile')}><span>Profile</span></a></li>
</ul>
</div>
<div id="main_data">
<ListProjects parentThis = {this} />
</div>
</div>
</div>
)
}


Problem is when i click on menu link component appears and disappears instantly and default component gets shown. Unable to find any specific solution online so please help what i am doing wrong.

Answer

The problem was that when we click on the href link then due to its default behavior page refreshes and component appears and disappears and then default component is shown. Its solution is we pass event on click and then prevent its default behavior like following

<li key="2"><a href="#" onClick={(evt)=>this.handleClick(evt, 'profile')}><span>Profile</span></a></li>

handleClick: function (event, name) {
        event.preventDefault();
        ...
}