I have a long list of data display divided into blocks with an edit button on side of each block, like this:
Whenever the edit button is clicked, i need to replace the display component with edit component, replacing the text with form like this
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?
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.
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!
/* 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.
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.
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>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With