Disable onClick event with JSON data - javascript

I want to disable a button click using a parameter from a JSON file:
JSON Parameter
"reactJson": {
"disable:"true"
}
My current onClick method works fine but if the parameter is true, I want to disable the onClick event. Currently my code looks like this:
let myJsonParam = reactJson.disabled //default is false
onClick
<button
onClick={() => {
handleSumbit();
}}
>
Exit and Save
</button>;
I know I can do this if it were a boolean:
{
!myJsonParam ? (
<button
onClick={() => {
handleSumbit();
}}
>
Exit and Save
</button>
) : (
<button
onClick={() => {
}}
>
Exit and Save
</button>
);
}
But since it is a string in JSON trueis there a different way to disable the button when the string is changed in JSON instead of replicating it and removing the onClick event ?

How do you think of this solution?
<button
onClick={() => {
if (!myJsonParam)
handleSumbit();
}}
>
Exit and Save
</button>

Related

how can i get my button to disappear? in reactjs

i am trying to make my button disappear if my textarea is empty
until now i have made some code for it but i still cant do it
in the code i am trying to make the css dynamic by having it change accoring to some ternery condition id the condition is met the css will allow the button to work and if not the other css class will turn the button off
my problem is that i want the on/off condition to work only when the textfield has more than one letter ( is not empty ) this will help me in my posting application as it will not post any empty posts instead only posts with letters and words ( non empty textarea) will post
here is the code:
function PostingNow() {
const [post, setPost] = useContext(Mycontext);
const tw = useRef('')
const[count,setCount] = useState(false)
return (
<div >
<textarea placeholder='whats up?' className="box" ref={tw}></textarea>
<button className={count?'tweetbutton':'unclickable'} >
Tweet
</button>
</div>
{post.map((post, i) => (
<Postingcomponent name ='user name'image={Photo} key={i} postContent={post}/>
))}
</div>
);
}
export default PostingNow
You can conditionally render your button in the jsx.
First make your textarea a controlled component so you have access to its state.
Then write
{textAreaText && <button ... />}
Make the textarea to be a controlled input
const [textarea, setTextarea] = useState("")
...
<textarea onChange={e => setTextarea(e.target.value)}>{textarea}</textarea>
Then for the button:
{textarea && <button ... />}
For better UX, it's recommended to disable the button instead of removing it from DOM.
<button disabled={!textarea} ... />
If you make the TEXTAREA tag something like:
<textarea placeholder='whats up?' className="box" ref={tw} class='unclickable'
onkeyup="fixPostButton(this, 'postButton', 'unclickable', 'tweetbutton');">
And make the BUTTON:
<button id="postButton" class="unclickable">Tweet</button>
Then this javascript will change the class after each keystroke:
<script>
function fixPostButton(txta, butn, isempty, notempty) {
var classX = (txta.value == '') ? isempty : notempty ;
document.getElementById(butn).className = classX; }
</script>

ReactJS // SearchBar onClick button

I created this search bar for an API. As you can see, the search bar is working with an onChange event. The user is searching the movie thanks to the title. I would like to search a movie with an onClick event with the button. For example, I'm searching Titanic, only this movie must appear.
<form action='/' methode='get' className='Search-Bar'>
<input
type='text'
id='searchbar'
className='searchbar'
placeholder='Rechercher un titre, un réalisateur...'
onChange={(e) => {
setSearchMovie(e.target.value);
}}
/>
<button className='search-button'>
<AiOutlineSearch /> OK
</button>
</form>
This is my code for the filter :
const allMovies = movies
.filter((value) => {
if (searchMovie === '') {
return value;
} else if (value.title.includes(searchMovie)) {
return value;
}
})
.map((movie, index) => {
return ( .............
It's working but I don't know how to search a movie thanks to the button... do you know how can I do this ??
Thank you !
Assuming your onClick is on the button it would be something like this, where you set the value of the movie as the value of the input field.
With your onChange set a value in the component for searchFieldValue and use it with the onClick. Ps your code is only html and JS as far as i can see, not a react related issue.
<button
className='search-button'
onClick={(e) => {
setSearchMovie(searchFieldValue);
}}
>
<AiOutlineSearch /> OK
</button>

Event object from onClick event couldn't access one of the props on the element in react

The program logic for the section where I run into trouble is that the function, named handleOperation, for handling state change(this.setState) will be invoked and supplied with two arguments once the corresponding buttons are clicked and the event is triggered, which calls handleOperation function and passed two arguments(obtained from event.currentTarget) to it. However, the console.log prints "submit" for the prop("type") that I intend to grab(It should have returned the value for "type"-either "sesnLength" or "brkLength" in this case)
This is the link to the project I am currently working on.
The following is the code snippet for my class component(parent component) where I supply child component(TimerLengthControl) with "type" property.
render(){
return(
<div>
<TimerLengthControl
title="Break Length"
titleID="break-label"
decrementID="break-decrement"
incrementID="break-increment"
spanID="break-length"
span={this.state.brkLength}
type="brkLength"
onClick={this.handleBreakLength}
/>
<TimerLengthControl
title="Session Length"
titleID="session-label"
decrementID="session-decrement"
incrementID="session-increment"
spanID="session-length"
span={this.state.sesnLength}
type="sesnLength"
onClick={this.handleSessionLength}
/>
<TimerControl
sessionLength={this.state.sesnLength}
onClick={this.handleReset}
/>
</div>
);
}
The onClick events are set up here on button elements in my child component(TimerLengthControl) from which the "type" and "value" will be fetched once this event is triggered.
const TimerLengthControl=(props)=>(
<div className="LengthContainer">
<div className="controlTitle" id={props.titleID}>{props.title}</div>
<div>
<button
id={props.decrementID}
value="-1"
type={props.type}
onClick={props.onClick}
>
<i className="fas fa-arrow-down"></i>
</button>
<span id={props.spanID}>{props.span}</span>
<button
id={props.incrementID}
value="+1"
type={props.type}
onClick={props.onClick}
>
<i className="fas fa-arrow-up"></i>
</button>
</div>
</div>
)
Here are the functions defined for handling the click event and some operations and this is also where I run into trouble. The console.log(e.currentTarget.type) prints "submit" rather than sesnLength or brkLength. I want to pass either of these along with "value" as arguments to the function "handleOperation" to update the parts of the state intended.
handleOperation(stateToChange,amount){
this.setState({[stateToChange]:this.state[stateToChange]+amount})
}
handleBreakLength(e){
console.log(e.currentTarget.type)
const {type, value}=e.currentTarget
this.handleOperation(type,value)
}
handleSessionLength(e){
const {type, value}=e.currentTarget
this.handleOperation(type,value)
}
Issue
The only valid values for the type attribute for HTML button elements is "submit", "button", and "reset". This is why you are seeing the console log "submit" always.
Solution
I suggest converting the handleBreakLength and handleSessionLength click handlers to curried functions to close over a type key for the state updates.
handleBreakLength(type) {
return (e) => {
console.log(type);
const { value } = e.currentTarget;
this.handleOperation(type, value);
};
}
handleSessionLength(type) {
return (e) => {
console.log(type);
const { value } = e.currentTarget;
this.handleOperation(type, value);
};
}
Remove the type prop and close over the "types" you want passed to the handlers.
<TimerLengthControl
title="Break Length"
titleID="break-label"
decrementID="break-decrement"
incrementID="break-increment"
spanID="break-length"
span={this.state.brkLength}
onClick={this.handleBreakLength("brkLength")} // <-- close over type
/>
<TimerLengthControl
title="Session Length"
titleID="session-label"
decrementID="session-decrement"
incrementID="session-increment"
spanID="session-length"
span={this.state.sesnLength("sesnLength")}
onClick={this.handleSessionLength("sesnLength")} // <-- close over type
/>
In TimerLengthControl hardcode a type="button" attribute so you won't accidentally submit any enclosing form elements.
<button
id={props.decrementID}
value="-1"
type="button"
onClick={props.onClick}
>
<i className="fas fa-arrow-down"></i>
</button>
<span id={props.spanID}>{props.span}</span>
<button
id={props.incrementID}
value="+1"
type="button"
onClick={props.onClick}
>
<i className="fas fa-arrow-up"></i>
</button>

Validating a value when button is pressed before passing it

Hi I am new to React and I am a little bit confused on how to validate a value before passing it to the partialRefund function I have.
I am trying to set a simple validation to make sure the value is not empty and numeric before passing it to the partialRefund function.
The first line is the code I currently have. The second line is the code I am trying to write for the validation but it is not working.
Any help would be really appreciated! Thanks!
//Current code
{partialRefundSelected ? <div> <input id={`partial_refund_${order_id}`} type='text'/> <button onClick={() => partialRefund(order_deets_obj,"partialRefund",document.getElementById('partial_refund_'+order_id).value)}> Refund Order </button> </div> : ""}
//Code I am trying to use
{partialRefundSelected ? <div> <input id={`partial_refund_${order_id}`} type='text'/> <button onClick={(validateValue(document.getElementById('partial_refund_'+order_id).value)) => partialRefund(order_deets_obj,"partialRefund",document.getElementById('partial_refund_'+order_id).value)}> Refund Order </button> </div> : ""}
On the second line i am trying to pass a function that will validate the value and the pass it to the partialRefund function. But it doesnt seem to be working :(
Use this:
{
partialRefundSelected ?
<div>
<input id={`partial_refund_${order_id}`} type='text'/>
<button onClick={() => {
const validatedValue=validateValue(document.getElementById('partial_refund_'+order_id).value));
partialRefund(order_deets_obj,"partialRefund",validatedValue);
}}> Refund Order
</button>
</div> :
""}
You can do the validation in the onClick callback if you add curly brackets around the parttialRefund call.
export default function App() {
const partialRefundSelected = true;
const order_id = 1;
const order_deets_obj = { deets: "good deets" };
const partialRefund = (deets, someString, someValue) => {
console.log(deets, someString, someValue);
};
return partialRefundSelected ? (
<div>
<input id={`partial_refund_${order_id}`} type="text" />
<button
onClick={() => {
const value = document.getElementById("partial_refund_" + order_id)
.value;
// Do validation here
if (value === "I LOVE CATS") {
partialRefund(order_deets_obj, "partialRefund", value);
}
}}
>
Refund Order
</button>
</div>
) : (
""
);
}
While this is an option in react, I would suggest making your input a Controlled Component. This would allow you to keep the input's text in state instead of needing to pull the text off of the element after a click. Here is an example.

Having multiple buttons call a function in ReactJS

Sorry if the title is vague. My problem is that I have three button tags, and for each tag I want it to send a unique argument to selectSupplier(). However no matter what button I press selectSupplier() only receives the last value ("ultramar") as an argument.
selectSupplier(supplier){
this.props.Obj.supplier = supplier
}
render() {
//console.log("SUPPLIER", this.props)
return (
<div>
<button onClick={this.showMenu}>
Select Supplier
</button>
{
this.state.showMenu
? (
<div
className="menu"
ref={(element) => {
this.dropdownMenu = element;
}}
>
<button value="Husky" onClick={this.selectSupplier("Husky")}> Husky </button>
<button value="Shell" onClick={this.selectSupplier("Shell")}> Shell </button>
<button value="Ultramar" onClick={this.selectSupplier("Ultramar")}> Ultramar</button>
</div>
)
: (
null
)
}
</div>
);
You can call like this :
this.selectSupplier.bind(this,"Husky");

Categories

Resources