score:0

toggleTheme() {
  this.setState(state => ({
    isLightMode: !state.isLightMode,
  }), () => {
    this.props.onChangeMode(this.state.isLightMode);
  })
}

score:0

import React from 'react'
import Layout from '../layouts/layout'
import ThemeContext from '../context/ThemeContext'
import AvatarLight from '../../content/assets/img/avatar-light.png'
import AvatarDark from '../../content/assets/img/avatar-dark.svg'

export default class Home extends React.Component {
  static contextType = ThemeContext

  render() {
    const { isLightMode, toggleTheme } = this.context
    return (
      <nav>
        <a onClick={toggleTheme}>{isLightMode ? 'Light mode' : 'Dark mode'}</a>
      </nav>
    )
  }
}

score:1

const Main = props => {
  return (
    <main className="main">
      <div>lightmode:{String(props.isLightMode)}</div>
      <div className="container">
        {React.cloneElement(props.children, props)} // pass props data to children
      </div>
    </main>
  );
};
const Home = props => {
  return <>{props.isLightMode ? "AvatarLight" : "AvatarDark"}</>;
};

score:2

export default class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isLightMode: true };
    this.toggleTheme = this.toggleTheme.bind(this);
  }

  toggleTheme() {
    this.setState(state => ({
      isLightMode: !state.isLightMode
    }));
  }

  render() {
    return (
      <Layout isLightMode={this.toggleTheme} toggleTheme={this.toggleTheme}>
        <img src={this.isLightMode ? AvatarLight : AvatarDark} />
      </Layout>
    );
  }
}

const Layout = ({ children, isLightMode }) => {
  return (
    <div>
      <Navigation isLightMode={isLightMode} onToggleTheme={this.toggleTheme} />
      {children && <Main isLightMode={isLightMode}>{children}</Main>}
    </div>
  );
};

Related Query

More Query from same tag