Check for a value onClick react - javascript

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

Related

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

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.

Input type checkbox issues: checkbox.value and setState working incorrectly on first click [duplicate]

This question already has answers here:
setState doesn't update the state immediately [duplicate]
(15 answers)
Closed 4 years ago.
I have the below simplified code with a checkbox that is intended to change state onClick, but I am not able to get the right value when clicked. It is in a React project with no jQuery.
The state element confirmCheck is initialized false, then the handler, handleConfirmClick is called onClick of the checkbox, and setState is called to turn confirmCheck to true. On the first click, the setState does not turn true, but on subsequent clicks, it toggles. This seems to be common problem fixed using jQuery.
The input value is set to this.state.confirmCheck somewhat in line with React docs
(https://reactjs.org/docs/forms.html), and the value in the appears element toggles correctly, but when I console.log checkBox.value, the value is false(!?) when it is true inside the element.
Based on my reading, the problem seems to be something to do with the DOM rendering the input, but I cannot find a clean solution. If all else fails, I could use a variable to test and pass click, but I would like to use state if possible.
What am I doing wrong?
class Edit extends Component {
constructor(props) {
super(props);
this.state = {
confirmChecked: false
};
}
handleConfirmCheck(event) {
const checkBox = document.getElementById('editConfirmCheck');
this.setState({ confirmChecked: !this.state.confirmChecked });
console.log(this.state.confirmChecked);
//logs false on first click
console.log(checkBox);
// on first click, logs <input type="checkbox" id="editConfirmCheck" value="true">
console.log(checkBox.value);
// logs false!!?? on first click
}
renderEditForm() {
return (
<div>
<label className="confirm-radio">
<input type="checkbox" id="editConfirmCheck" value={this.state.confirmChecked} onChange={this.handleConfirmCheck.bind(this)} /> Check to confirm changes then submit
</label>
</div>
);
}
}
render() {
return (
<div>{this.renderEditForm()}</div>
);
}
}
export default Edit
That's because setState is asynchronous. Before it will update and change the DOM, your console log has already been called.
I have tested your code the only mistake you did was typo in render method it should be this.RenderEditForm() instead of this.renderEditForm() and everything seems to be working fine
Here is what you want.
You have closed the class body in the RenderEditForm() method.
Also you are trying to call a method that has never defined.
<div>{this.renderEditForm()}</div>
https://codesandbox.io/s/2vjmp10xky

Semantic UI React, Dropdown Selection

Please take a look at my code for Dropdown,
I'm using the semantic ui react dropdown on an EditProfile component. I have pasted a sample code here, https://codesandbox.io/s/m4288nx4z8, but I could not get it to work because I'm not very familiar with functional components in React, I've always used Class component. But you can check the full code for the whole component below in the github gist.
https://gist.github.com/mayordwells/b0cbb7b63af85269091f1f98296fd9bb
Please, I need help on inserting values from multiple select options of a Dropdown into the Database and also a way to display that back upon viewing the profile edit page again.
I'm using semantic-ui-react in react + rails app.
Also when I insert a value using a normal drop down without multiple select, the value gets persisted into the database.
<Dropdown
placeholder='Select Country'
fluid
search
selection
options={countryOptions}
name='country'
defaultValue={this.state.extraInfo.country}
onChange={(e) => this.handleExtraInfoChange('country', e)}
/>
This code handles change for the dropdown elements.
handleExtraInfoChange = (name, event) => {
let value;
if (event.target.value !== undefined) {
value = event.target.value;
} else {
value = event.target.textContent;
}
let newExtraInfo = Object.assign(this.state.extraInfo, { [name]: value })
this.setState({ extraInfo: newExtraInfo});
}
But when I visit the page again, I get a white blank in the input box. Here's a screen pic for that. When I comment out the defaultValue or value property(i have tried with defaultValue and value), the white blank disappears, but the value picked by a user is also not seen.
Please advice what is a possible solution to this misbehavior? And what is the best way to insert multiple values into the Database?
Thanks in advance for your time.
A functional component does not have state, it's used for composition; you want to store state, so you either have to create a Component class or you need an external state container like redux.

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