My component is a header that contains primary and secondary navigation. So far I am dealing with primary navigation only, which chooses between large sections of the website. The state is lifted up to the main Header component, while the UpperMenu component only receives event listener and active link ID as props.
The problem is that while the state changes are conducted correctly, when the mounting is executed, the state gets changed back to initial value. This causes a "blink" in CSS, meaning that the view is rendered correctly and after a tiny second it goes back to the initial link being selected. I don't know what can possibly cause such behavior and would appreciate help.
Header.js:
import React from 'react';
import UpperMenu from './UpperMenu';
import TopHeader from './TopHeader';
import styles from './Header.css';
const sections = [
["/sec0","section0"],
["/sec1","section1"],
["/sec2","section2"]
];
class Header extends React.Component {
constructor(props){
super(props);
this.state = {section: 0,
submenu: 0};
}
// HERE THE STATE IS SET CORRECTLY
onSectionClick(event){
console.log(event.target.id);
this.setState({section:event.target.id[8]},
function () {console.log(this.state);});
}
// HERE PROBLEMS OCCUR, STATE IS INITIAL
componentDidMount(){
console.log(this.state);
}
render() {
return (
<header id={styles.header}>
<TopHeader />
<UpperMenu sections={sections}
activeSection={sections[this.state.section][1]}
onSectionClick={this.onSectionClick.bind(this)}/>
</header>
);
};
}
export default Header;
UpperMenu.js:
import React from 'react';
import styles from './UpperMenu.css';
import {Link} from 'react-router';
class UpperMenu extends React.Component{
render(){
var activeSection = this.props.activeSection;
var onSectionClick = this.props.onSectionClick;
var sectionIndex = -1;
return(
<div className={styles.mmenu}>
<ul className={styles.normal}>
{this.props.sections.map(function(section){
sectionIndex++;
return(
<li key={section[1]}
id={"section_" + sectionIndex}
className={(activeSection === section[1]) ? styles.active : ""}
onClick={onSectionClick}>
<a id={"section_" + sectionIndex + "_a"}
href={section[0]}>{section[1]}</a>
</li>
)})}
</ul>
</div>);
}
}
export default UpperMenu;
P.S. I have tried to debug the lifecycle to determine at which point this happens and the problem begins at the componentDidMount.