Instructions for concealing a parent div and substituting it with a different div upon the user's click on a button nested within the parent div

I am working on a component that consists of two buttons. The goal is to hide the entire component when one of the buttons is clicked and replace it with another component.

Although I have successfully hidden the clicked button, I am struggling to hide the parent component entirely when the child button is clicked.

Can anyone suggest the best approach to achieve my desired outcome?

Below is the current code snippet (which only hides the pressed button):

    const ParentComponentStyle = {
      width:300,
      height:60,
      backgroundColor:"#343458"
    };

    class ParentCompnent extends React.Component {

     constructor(props){
         super(props) 
            this.state = {
               buttonPressed:false,
               opacity:1
         }
       this.handleClick = this.handleClick.bind(this);
      }


      handleClick(evt) {
        this.setState({
          buttonPressed: !this.state.buttonPressed,
          opacity: 0,
       })
     }

    render(){
      return(
        <div className="DivToHide" style={ParentComponentStyle}>
            <div onClick={this.handleClick} style={{float:'left'}}>{this.props.children[0]}</div>
            <div onClick={this.handleClick} style={{float:"right", opacity: this.state.opacity}}>{this.props.children[1]}</div>
        </div>


       );
    }
}



export default ParentComponent;

Here is the component that should be displayed once the initial component is hidden:

  const ShowThisDivStyle = {
      width:300,
      height:200,
      backgroundColor:"#343458"
  };

  var ShowThisDiv = React.createClass({
  render: function(){
      return(
      <div style={ShowThisDivStyle}>
            <div style={{float:'left'}}>{this.props.children[0]}</div>
            <p style={{float:"left", color:"white",marginTop: "7px"}}>{this.props.children[1]}</p>
            <div style={{float:"right"}}>{this.props.children[2]}</div>
            <p style={{float:"right",color:"darkGray",paddingRight: "46px", marginTop: "0",fontSize:'12px', marginBottom:"0px"}}>{this.props.children[3]}</p>
            <div style={{textAlign:"center"}}>{this.props.children[4]}</div>
    </div>  


      );
    }
 });

 export default ShowThisDiv;

Answer №1

Follow this structured guide to hide buttons and display the relevant Component using a single handleClick method: http://codepen.io/PiotrBerebecki/pen/BLGmvd

const StylishParentComponent = {
      width:300,
      height:60,
      backgroundColor:"#343458"
};


class ParentPiece extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      buttonTriggeredA: false,
      buttonTriggeredB: false
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(evt) {
    this.setState({
      [`buttonPressed${evt.target.id}`]: !this.state[`buttonPressed${evt.target.id}`]
    });
  }

  render() {
    let renderContent;

    if (this.state.buttonPressedA) {
      renderContent = (
        <DivA>
          <p>Child A</p>
          <p>Another Child A</p>
          <p>Yet Another Child A</p>
          <p>One More Child A</p>
          <p>Final Child A</p>
        </DivA>
      );
    } else if (this.state.buttonPressedB) {
      renderContent = (
        <DivB>
          <p>Child B</p>
          <p>Another Child B</p>
          <p>Yet Another Child B</p>
          <p>One More Child B</p>
          <p>Final Child B</p>
        </DivB>
      );

    } else {
      renderContent = (
        <div className="HiddenDiv" style={StylishParentComponent}> 
          <button onClick={this.handleClick} id="A">
            Show DivA
          </button>
          <button onClick={this.handleClick} id="B">
            Show DivB
          </button>
        </div>
      );
    }

    return(
      <div>  
        {renderContent}
      </div>
    );
  }
}


const StyleDivA = {
  width:300,
  height:200,
  backgroundColor:"green"
};

const DivA = React.createClass({
  render: function() {
    return(
      <div style={StyleDivA}>
        Div Section A
        <div style={{float:'left'}}>{this.props.children[0]}</div>
        <p style={{float:"left", color:"white",marginTop: "7px"}}>{this.props.children[1]}</p>
        <div style={{float:"right"}}>{this.props.children[2]}</div>
        <p style={{float:"right",color:"darkGray",paddingRight: "46px", marginTop: "0",fontSize:'12px', marginBottom:"0px"}}>{this.props.children[3]}</p>
        <div style={{textAlign:"center"}}>{this.props.children[4]}</div>
      </div>
    );
  }
});


const StyleDivB = {
  width:300,
  height:200,
  backgroundColor:"red"
};

const DivB = React.createClass({
  render: function() {
    return(
      <div style={StyleDivB}>
        Div Section B
        <div style={{float:'left'}}>{this.props.children[0]}</div>
        <p style={{float:"left", color:"white",marginTop: "7px"}}>{this.props.children[1]}</p>
        <div style={{float:"right"}}>{this.props.children[2]}</div>
        <p style={{float:"right",color:"darkGray",paddingRight: "46px", marginTop: "0",fontSize:'12px', marginBottom:"0px"}}>{this.props.children[3]}</p>
        <div style={{textAlign:"center"}}>{this.props.children[4]}</div>
      </div>  
    );
  }
});


ReactDOM.render(
  <ParentPiece />,
  document.getElementById('app')
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The proper way of aligning text in the middle of a button

I'm currently working on designing a CSS button that will be placed in the top left corner and serve as a back button to the previous page. However, I am facing challenges when it comes to centering the arrow or text perfectly in the middle of the but ...

Communicating data transfer between two Node.js servers through the use of the Node Serial Port technology

How can I send the message "Hello world" from one nodejs server to another using node-serialport? I have confirmed that the radios connecting the two servers are properly connected as they are displaying buffer information after running my current code. ...

Obtaining the jqXHR object from a script request loaded within the <head> tag using the <script> tag

Is it possible to retrieve the jqXHR object when a script loaded from a script tag within the head tag? function loadScript(url){ const script = document.createElement("script"); script.src = url; // This line will load the script in the ...

When the click event is triggered on the modal, the page suddenly jumps to the top while applying the style of hiding the element

After implementing a modal that appears upon clicking an element on my webpage, I encountered an issue when trying to close it. I added an event listener to the 'close' link element in the top right corner of the modal with the following code sni ...

Create styles for each component based on their specific props when designing a customized Material-UI theme

I am having trouble styling the notchedOutline of a disabled <OutlinedInput /> in my custom MUI theme. My goal is to make the border color lighter than the default color when the input is disabled. Here is what I have attempted so far: const theme = ...

Could this be a problem with synchronization? Utilizing Google Translate to link-translate terms

Trying to create a script that will show how a word changes through multiple translations using Google Translate, but struggling with Javascript. The problem I'm facing is hard to pinpoint: function initialize() { var word = "Hello"; var engl ...

Fixing the hydration error in Next 13 can be challenging, especially when it occurs outside of a Suspense boundary

Encountering an issue while working with Next.js 13: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected server HTML to contain a matching <div> in <html>. Every time I attempt to r ...

`How can parameters be passed to a controller while utilizing routes?`

Within my application, I am utilizing ngRoute to load views. .state('ReportViewer', { url: "/ReportViewer", controller: 'ReportViewerControl', templateUrl: "views/Report_viewer.html" }) The ...

Determining the best orientation for a marker or pointer on a 3D .obj Object in order to create the illusion that it is pointing towards a specific area of the object

I am trying to achieve a similar effect to the one shown in this example ( https://jsfiddle.net/xg1o4ekr/378/ ), but with different shapes of 3D objects and markers coming outwards. Since my 3D object is not a circle, the code provided in the link above ...

Sending variables to imported files using Typescript

Couldn't find it in the documentation. My question is, does TypeScript have a similar feature to this? file1.js module.exports = (service) => { service.doSomeCoolStuff(); } file2.js const file2 = require('./file2')(service) I need ...

Arrange the children dynamically

I'm struggling to position my ul menu at the top right corner of the page and adjusting the spacing between the items. Whenever I try to add padding, it disrupts the inline display. What am I missing here? #menu { top:0; width:100%; hei ...

Does applying a style to an element that already has the same value result in a decrease in performance? Alternatively, do all browsers simply overlook it?

Assuming I have an element with the style top: 5px, and then I execute element.style.top = "5px";, will the browser readjust its position and trigger a layout again? Or does it recognize that there is no need to change anything? (Is this behavior specified ...

Using Node.js to include multiple parameters in a route by using regular expressions

Trying to create my first route with multiple params filtered using regexs: router.get('/circle/:radius([0-9]{1,3})/Xposition/:x(\-?[0-9]{1,3}(\.[0-9]{1,9})?)/Yposition/:y(\-?[0-9]{1,3})', function(req, res, next) { console.log(&a ...

When using nativescript-vue to navigate to a Vue page, the props are cached for later

A couple of days back, I managed to resolve the issue I was facing with navigating through Vue pages. However, after fixing that problem, I made an error by mistakenly attempting to pass an incorrect key value to the Vue page I was redirecting to. When th ...

Encountering issue with express 4.x bodyparser functionality

I recently updated my body-parser to the latest version (1.17.1) and made sure to organize my code as advised by others. import express import body-parser app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended : fa ...

Dynamic React animation with sliding elements

When jumping between the second and third "page" of content, I am unable to determine the reason why it is happening. The content is displayed as an absolute position. Check out the sandbox here: https://codesandbox.io/s/nostalgic-bhabha-d1dloy?file=/src ...

Implementing an API route to access a file located within the app directory in Next.js

Struggling with Nextjs has been a challenge for me. Even the most basic tasks seem to elude me. One specific issue I encountered is with an API call that should return 'Logged in' if 'Me' is entered, and display a message from mydata.tx ...

What is the best way to invert a filter in JavaScript?

Is there a way to create a function called "reverse" that can filter out elements not filtered by the original filter? I have been trying to find a solution, but it seems more complex than I thought. let f1 = e => e > 3; let f2 = reverse(f1); let ...

The occurrence of an unanticipated character '#' was found

I'm currently facing an issue while using webpack to load dependencies. Whenever I execute the npm run dev command, I encounter the following error: Uncaught Error: Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: ...

Unable to Change Color of Buttons in Jquery Mobile

Utilizing JQuery mobile for my application. <input data-mini="true" data-inline="true" data-theme="d" value="Login" type="submit" /> When clicking the button in iOS, the color does not change immediately. It only changes when the button is held for ...