ReactJS - How does one delete a button component, that was just clicked? - javascript

My aim is to delete the button, I have just clicked. I understand there may be numerous ways such as creating a deleteButton component, and setting the state appropriately.
However, my return function in the main App component will also render another button (this I can do), but I think this may add to the complexity.
I'm currently struggling to pin-point the ideal solution, so please help.

Okay, so I've managed to solve my question, although I'm sure there's other ways too.
To further clarify...
I had a form which I wished to render, when clicking on a 'Create' Button.
At the same time, I wished to remove the 'Create' button, once clicked.
The end result is to only display the form and nest a new button in the return function.
1) Set the initial state of the form to false:
this.state = {
displayForm: false,
}
2) Then use setState within the displayForm function to allow for the change in state, once the button is clicked:
displayForm(){
this.setState({
displayForm: !this.state.displayForm {/* true */}
})
}
3) set a style object within the render function, such as:
render() {
const btnStyle = {
display: 'block',
} ...
4) Use an IF statement to change the display style of the button if the form has been rendered
if(this.state.displayForm){
btnStyle.display = 'none'
}
5) Now, within the return function, use your JSX tags appropriately and call the function onClick, as well as the style to be applied.
<Button
style={btnStyle}
onClick={() => {
this.displayForm()
}}>Create</button>
{this.state.displayForm && ([
<Form />,
<br />,
<Button>Add Schema</Button>,
])}
NOTE: the < Form /> and < Button /> components have been imported and added here.
So, once the 'Create' button has been clicked, the form displays (true), and thereby the 'Create' button disappears from the Virtual DOM. I've also nested another (new) button as intended, underneath the form.

Related

How to hide autocomplete box on Blur in React?

Can't solve a problem. Could someone help me?
I'm building a form and have an autocomplete box. The problem is that if I click somewhere on a page (except for the suggestion item) it doesn't hide. Where should I add setIsAutoCompelte(false) so that it hides?
State
// if true then show the box
const [isAutoComplete, setIsAutoCompelte] = useState(false);
onHandleChangeInput (if input.length > 3)
// show the box
setIsAutoCompelte(true);
onSuggestionClick (if I click on item in autocoplete box)
// hide the box
setIsAutoCompelte(false);
I do not provide full code because it's too big and I'm sure nobody would take a look at it.
You could have an onClick on App that changes the state if the clicked target didn't have the className of the input. You'd need to apply a className such as "autoCompleteBox" to every element/component where you want isAutoComplete to be true.
const clickAnyWhereBut = (e, className) => {
if (!e.current.target.classList.contains(className)) {
setIsAutoCompelte(false); /* you have a typo for "complete/compelte" */
}
}
<div className="App" onClick={() => clickAnyWhereBut("autoCompleteBox")}></div>
This is a lot easier if you're using redux because you wouldn't need to pass down the setIsAutoCompelte[sic] state.

Unable to render component in a new page on a new route on button click

I am very new to react and just started to build a basic crud application with it. Everything is done besides the update functionality, i got stuck there.I have several bootstrap cards with 2 buttons , delete and update.The data comes from a mysql database and was persisted with hibernate (spring boot on backend).The update button when pressed should pass the id and render a new component(on a different route, guess i need to use Link here) in which a filled form with the respective objects details is presented. Once the user updates the form and clicks submit, he should be redirected to the Cards page. So far i am stuck at the button + Link and rendering the new component phase and for some reason i can't seem to understand how to make it work.This is my code so far
this is my JSX in which i have the Update button which is in the render method of CarList component which has all the cards.
<ReactBootstrap.Card.Body>
<ReactBootstrap.Card.Title>{cars.mark}-{cars.model}</ReactBootstrap.Card.Title>
<ReactBootstrap.Card.Header>Price: {cars.price}</ReactBootstrap.Card.Header>
<br />
<h6>Fabricated: {cars.year}</h6>
<h6>{cars.fuel}</h6>
<ReactBootstrap.Button variant="success" className="cardButtons" id="cardButtonGreen" onClick={() => this.handleClickUpdate(cars.id)}> Update</ReactBootstrap.Button>
<ReactBootstrap.Button variant="danger" className="cardButtons" id="cardButtonRed" onClick={() => this.handleClickDelete(cars.id)}> Delete</ReactBootstrap.Button>
</ReactBootstrap.Card.Body>
</ReactBootstrap.Card>
</div>
}
<br />
</div>
this is my CarList class and the constructor
class CarList extends Component {
constructor(props) {
super(props)
this.state = {
cars: [],
error: "",
deleteError: "",
updateError: "",
updateCarId: null,
buttonWasPressed: false
}
}
here i have the function that is triggered on click.I am sating the state to the id of the object that is in that specific card where the update button is.
handleClickUpdate = (carId) => {
console.log(carId);
this.setState(
{
updateCarId: carId,
buttonWasPressed: true
}
)
}
and lastly i am rendiring the Component MyComp i want to render by passing in the ID.Line is located in component CarList right under where the Card is.
{this.state.buttonWasPressed && <MyComp carId={this.state.updateCarId} />}
What this code gives me so far, is that i am able to set the state as the id, and then use the button to display the component, but it is displayed on the same page, right under the card (where the line of code is also located) instead of displaying it in a new page on a new route.I have tried adding Link,Switch, Route, Router, but i am afraid i am not sure how to use it in this exact context with the button, and it is confusing to me so i was not able to make it work.Can you please help me render "MyComp" on a new page with that id ?
Any help would be greatly appreciated.
what you need is a global store, such as Redux or Mobx. That way you can update the state with relevant data and retrieve them on the new page.
If you need a workaround, you could use history.pushState()
Basically you can push to your location and with it a state.
And on the next page, which is MyComp in this case, you could use history.state to retrieve the pushed data.

Check for a value onClick react

In my render method i render some cards that all have button and when i click on the button i want to disabled them.
Those buttons are checking if the value of the array is true and if it is it's disabling the button but this is only working when i refresh the page and i want the button to be disabled directly on click
Here is my try
//this is checking from my database if it include the id of the pokemon that i want to get
const check = pokemon.id
const newPoke = getPokemon.includes(check);
// Here is the button that is getting disabled only if newPoke return true
<Button isDisabled={newPoke}/>
Everything work correctly when i refresh the page the buttons that i clicked previously get disabled but not onClick directly.
I think after i click i have to re-check for newPoke but i'm not sure how to include it in the button
You are using props to pass variable from parent to children(Button).
reactjs documentation states react props are read-only
If you are planing to change the values of newPoke then you should rethink your structure and maybe its best to use states in your example
For example here
<Button isDisabled="newPoke"></Button will only be checked at initialization stage since its a react prop. but if you used state which gets updated with every new action you can have a true one-way binding and your ui would reflect data changes quickly
store the newPoke in state and change it's value when the button is clicked. and use that value in button isDisabled prop. try something like this
state={
isDisabled: false;
}
handleClick=(isDisabled)=>{
this.setState({isDisabled});
}
//this is checking from my database if it include the id of the pokemon that i want to get
const check = pokemon.id
const newPoke = getPokemon.includes(check);
// Here is the button that is getting disabled only if newPoke return true
return(
<Button isDisabled={this.state.isDisabled} onClick={()=>this.handleClick(newPoke )}/>
);
i think if you want get value from database you can use componentDidMount().
and your value you can save while in state. and then in function handleClick you can change this state
for example :
handleClick = () => {
const value = this.state.valueFromDataBase
this setState({valueFromDataBase: false})
}
and in render you declare this value state
render(){
return(
<Button defaultValue={this.state.valueFromDataBase} onCLick={this.handleClick} />
)
}
please correct my answer if I am wrong in responding to your question

How to add disabled attribute via prop to a button in react?

I am creating a custom button component in react. I want to pass a prop to that button, based on the value of which button gets enabled or disabled.
My problem is
- The mere presence of the disabled property disables the element, so I cannot set its value as "false". Even the following code is disabling the element
<input type="button" id="myBtn" value="Submit" disabled="" />
I need to either remove the attribute completely or set its property via javascript.
document.getElementById("myBtn").disabled = true;
My custom button component is -
import React from 'react';
const CustomButton = ({ whenClicked, classNames, buttonText, isDisabled }) =>
(
<button
onClick = {whenClicked}
className = {`btn ${classNames}`}
type = "button"
disabled = {isDisabled}
>
{buttonText}
</button>
);
export default CustomButton;
isDisabled is a boolean value.
One more thing, I lost the default submit behavior of button while using custom button. Now I always need to pass a click handler. Is there any way to achieve the same behavior again?
What you currently have should work perfectly fine. Be careful that when you use CustomButton you don't send in the value for disabled as a string. That will make it disabled regardless of what you pass in. Instead, you need to pass in a boolean, that's in JSX syntax.
Here's a sample usage where you would put it inside of a render function of a component that uses the button:
...
render() {
<div>
...
<CustomButton
whenClicked={() => console.log('I just got clicked')}
buttonText="Some Button"
isDisabled={false}
/>
...
</div>
}
...
Basically, instead of false you could pass in something else. You could pass in a boolean value that's stored on the props of the container that holds the CustomButton.
You could say isDisabled={this.props.disableInnerButton} and it would work as you would expect. Changing the value of the boolean will disable or enable the button.
Below you can find a relevant answer I gave recently on a very similar topic:
Statement to add or not an attribute in JSX
At first it looks quite complicated to handle but, if we look at the problem I think we can achive it using css only by adding a class(selector) to the element
.disabled { pointer-events: none;}
or conditionally styling:
<button style={{pointerEvents: notValid ? "none" : "initial"}}> Submit </button>

React.JS, pass data between components

very new to react. you can say I have not yet started to think like React.
here is the problem:
<div>
<DropDown> </DropDown>
<Panel> </Panel>
</div>
In the dropdown, I select a value. Store it in state, as something as , currentLocation.
Then I go to Panel, hit a button, and I want to open a modal. When i open a modal, I need to pass the currentLocation to that model.
I can pass in arbitrary value to modal, but I cannot figure out a way to get the currently selected item from DropDown.
How do I get the value of the currently selected item to the Panel?
Am I even making sense?
When you call the setState in the dropdown that will force an update of the page.
Then if you call this.state in your component you should have the value you need there.
You should go over the basic tutorials to grasp the react basics.
But it goes like this:
getInitialState: function() {
return {
myVar: ''
//set your variables here
//getInitialState will get called before the component gets mounted
};
},
myCustomFunction: function(newVariable) {
this.setState({
myVar: newVariable
});
},
render: function() {
return (
<div>
<input
onChange={this.myCustomFunction}
/>
<MyCustomComponent myProp={this.state.myVar}/>
//everytime the state changes MyCustomComponent will have that new value as a prop
</div>
);
}
There is a lot of ambiguity in your question but I'll try for the simplest case.
You have a Panel component and a Dropdown component.
You want to the Panel to have access to a value that was set when the Dropdown was used.
Solution: When the Dropdown is actuated, it creates an Action that Stores the selected value.
When the modal button in the Panel is actuated, it creates an Action that requires the DropDownStore. Then it decides what to do based on that value.
The pattern I am loosely describing is known Facebook's Flux architecture which is basically just a more specific application architecture for React applications similar to pub/sub or an event bus.

Categories