I have a toggle in the main component (show & hide a div), but I want to move the button that activates it to a secondary component. how do I do it?

Viewed 17

Here I have created the main component with a "Warning" heading inside it, by clicking the button you can hide the title or reveal it.

I created a secondary component called TEST1, I want to embed the button in it instead of the main component.

import React ,{Component} from 'react';
import './App.css';
import Test1 from './components/test1';
function WarningBanner(props) {
  return (
    <div className={props.warn ? "warning": "hide"}>
      <h1> Warning! </h1>
    </div>
  );
}
class App extends Component{
  constructor(props) {
    super(props);
    this.state = {showWarning: true}
    this.handleToggleClick = this.handleToggleClick.bind(this);
  }
  handleToggleClick() {
    this.setState(prevState => ({
      showWarning: !prevState.showWarning
    }));
  }
  render(){
    return (
      <div className="App">     
        <Test1 ></Test1>
        <div>
          <WarningBanner warn={this.state.showWarning} />
          <button onClick={this.handleToggleClick}>
            {this.state.showWarning ? 'Hide' : 'Show'}
          </button>
        </div>
      </div>
    );
  }
}
export default App;

1 Answers

You can put the button into Test 1 component and call the handleToggleClick function which is passed from the parent component (App - in your case).

It seems to like below:

import React ,{Component} from 'react';

// -----
// in Test 1 component
function Test1(props) {
   return (
     <div>
          <button onClick={props.handleToggleClick}>
            {props.showWarning ? 'Hide' : 'Show'}
          </button>
     </div>
   )
}
// ------

class App extends Component{
  constructor(props) {
    super(props);
    this.state = {showWarning: true}
    this.handleToggleClick = this.handleToggleClick.bind(this);
  }
  handleToggleClick() {
    this.setState(prevState => ({
      showWarning: !prevState.showWarning
    }));
  }
  render(){
    return (
      <div className="App">     
        <Test1 
            handleToggleClick={this.handleToggleClick} 
            showWarning={this.state.showWarning}
        />
        <div>
          <WarningBanner warn={this.state.showWarning} />
        </div>
      </div>
    );
  }
}
export default App;
Related