Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a component with another one upon event (button click) in react js

Tags:

reactjs

jsx

I have a long list of data display divided into blocks with an edit button on side of each block, like this: enter image description here

Whenever the edit button is clicked, i need to replace the display component with edit component, replacing the text with form like this

enter image description here

what would be the best way to do this. I have tried putting the components inside state as list and replacing Display component with Form Component, when Edit is clicked so instead of returning this from render():

return(
 <Display />
 );

Now i am returning:

return(
 {this.state.components[0]}
  );

and when button is clicked doing this

this.setState({components:[<EditForm />]})

It works but i was wondering is storing Component and JSX inside state a good idea/ professional practice?

like image 722
Yogesh Avatar asked May 27 '18 12:05

Yogesh


People also ask

How do you change the component on a button click in React?

To update a component's state on click, add an onClick prop to an element and set it to a function. The function will be invoked every time the element is clicked, which allows us to update the component's state on click.

How do I pass onClick to another component?

You can also pass events like onClick or OnChange Just call an alert method in the childToParent function and pass that function as a prop to the child component. And in the child component, accept the childToParent function as a prop. Then assign it to an onClick event on a button. That's it!

How do you load a new component on a button click in react JS?

/* Write a button component */ import React from 'react'; const Button = (props) => { return ( <button>{props. text}</button> ); } export {Button}; What is this? import React from 'react'; const ListComponent = (props) => { return ( <div> <h1>{props.

How do you send state props to another component in React with onClick?

Sending state/props to another component using the onClick event: So first we store the state/props into the parent component i.e in which component where we trigger the onClick event. Then to pass the state into another component, we simply pass it as a prop.


1 Answers

you could do something like this: use a variable in state for knowing edit is clicked or not

state={
   isEdit:false,
  }

on click of edit: this.setState({isEdit:true})

in render() use conditional rendering:

render(){
   return(
    <div>
        {(!this.state.isEdit) ? <Display /> : <EditForm />}
     </div>
       )
     }
like image 64
aravind_reddy Avatar answered Oct 23 '22 08:10

aravind_reddy