Reputation: 27
I'm trying to set a toggle state in a react component but every time I click the title the page scrolls up. I tried adding e.preventDefault to the onClick function but it does nothing.
I'm pretty sure it's being caused by the dangerouslySetInnerHTML part of the jsx element.
Is there a way to prevent this behavior or perhaps a better way to do this?
this.props.page.acf.ios/android
is an html string that is being returned from WordPress JSON api and returns something like the following (using entities.decode to transform any html entities):
{
"ios": "<p><h1>How it works<\/h1><\/p>\n<p>Navigation menus are reached from the header by tapping an associated menu icon.<\/p>\n<p>When a user clicks on the hamburger icon in the header, the main navigation menu opens.<\/p>\n<p>The main menu can appear in several states:<\/p>\n<ul>\n<li>Logged Out<\/li>\n<li>Logged In<\/li>\n<\/ul>\n<p>Navigation menu items are displayed with title casing.<\/p>\n<p><img class=\"alignnone size-full wp-image-89\" src=\"http:\/\/mobilestyle.ups.dev\/wp-content\/uploads\/2015\/07\/logged-out.jpg\" alt=\"logged-out\" width=\"292\" height=\"519\" \/><\/p>\n"
}, {
"android": "<p><h1>Android stuff<\/h1><\/p>\n<p><img class=\"alignnone size-full wp-image-89\" src=\"http:\/\/mobilestyle.ups.dev\/wp-content\/uploads\/2015\/07\/logged-out.jpg\" alt=\"logged-out\" width=\"292\" height=\"519\" \/><\/p>\n"
}
Here's the component in question:
let MobileTabs = React.createClass({
getInitialState() {
return {
togglePage: false
}
},
handleClick(e) {
e.preventDefault();
this.setState({
togglePage: !this.state.togglePage
})
},
render() {
let acf = this.props.page.acf;
if (this.state.togglePage) {
return <div className="page__mobile_tabs">
<h2 onClick={this.handleClick}>Android</h2>
<div dangerouslySetInnerHTML={{__html: entities.decode(acf.android)}}></div>
</div>;
} else {
return <div className="page__mobile_tabs">
<h2 onClick={this.handleClick}>iOS</h2>
<div dangerouslySetInnerHTML={{__html: entities.decode(acf.ios)}}></div>
</div>;
}
}
});
module.exports = MobileTabs;
Upvotes: 0
Views: 1739
Reputation: 3485
It is possible that the scroll is being caused by the dom elements being removed and then added back in. If you add key
property that lets React know to re-use the dom element instead of removing and adding a new element. In this case, you'd want to use the same key in both the Android and ios cases.
return <div key="mobile_tabs" className="page__mobile_tabs">
If adding key
doesn't work, all try adding a min-height
in page__mobile_tabs
and see if that helps prevent the scroll. For testing, you could use a large height, like 1500px.
Upvotes: 1
Reputation: 232
have you tried wrapping the return
data of your render
function in parens?
javascript will otherwise implicitly insert a semicolon at the end of the line
Upvotes: 0