Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React component appears and disappears instantly

Tags:

reactjs

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.

like image 516
Afnan Nazir Avatar asked Dec 28 '25 08:12

Afnan Nazir


1 Answers

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();
        ...
}
like image 147
Afnan Nazir Avatar answered Dec 30 '25 22:12

Afnan Nazir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!