Bring Properties to the button in React js - javascript

I am trying build an booking app in react, can anyone suggest how can I bring the properties from the table to the button?
For example:
when the user click the select button on the first schedule, the schedule id and the training id of the first row, will be bringing to the select button to perform action. Any tips and helps are much appreciated in advance!
rendering table:
**booking() is my action
const bookBtn=(trainer_id, schedule_id)=>{
return(
<Button onClick={booking(trainer_id,schedule_id)} variant="danger">
Select
</Button>
)
}
const renderSchedule = (details, index) => {
return (
<tr key={index}>
<td>{details._id}</td>
<td>{details.trainer}</td>
<td>{details.date}</td>
<td>{details.startAt}</td>
<td>{details.endAt}</td>
<td>
{bookBtn(details.trainer,details._id)}
</td>
</tr>
)
}

Just pass a function to your onClick that invokes your custom handler with parameters:
const bookBtn = (trainer_id, schedule_id) => {
return(
<Button onClick={() => booking(trainer_id, schedule_id)} variant="danger">
Select
</Button>
);
}
If booking is indeed a handler, of course.

Related

Passing function and params through react props

I have an dropdown menu with buttons for the dropdown elements and pressing them causes an fucntion call.
`
<div className = "dropdown-container">
<button className = "dropdown-button"> Sort </button>
<div className = "dropdown-content">
<button className = "sort-button" onClick={() => changeFilter(['sort=-Covered_distance'])}> Furthest </button>
<button className = "sort-button" onClick={() => changeFilter(['sort=+Covered_distance'])}> Shortest </button>
<button className = "sort-button" onClick={() => changeFilter(['sort=-Duration'])}> Longest </button>
<button className = "sort-button" onClick={() => changeFilter(['sort=+Duration'])}> Fastest </button>
</div>
</div>
Im trying to clean up my code as I have multiple dropdown menus next to each other with the same principle. I thought about making a react component that has the structure of the dropdown menu but as I have an function call in it I need to pass this through also so like.
<div className = "filters-container">
<Dropdown changeFilter = { () => changeFilter() }/>
</div>
Now this works as it calls the function changeFilter(), but none of the params from the other component gets called with the call so it basically calls only changeFilter(), when I press any of the buttons. How can I get the params with the call?
You must pass the argument in the changeFilter prop.
For example:
<div className="filters-container">
<Dropdown changeFilter={() => changeFilter(['sort=-Covered_distance'])} />
</div>
Here's a working example:
https://codesandbox.io/s/falling-currying-kd0oco?file=/src/App.js
The problem here is that when you pass a function as a prop, you can't change their parameters inside the component, the parameter has to be passed from the parent.
Pass the paramter ['sort=-Covered_distance'] in changeFilter function like this:
<div className = "filters-container">
<Dropdown changeFilter={() => changeFilter(['sort=-Covered_distance'])} />
</div

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>

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.

OnClick function not working with custom button Component

I am passing the value of the button the user clicks on to an array with the following function.
const [pizzaSize, setPizzaSize] = useState("Choose your Pizza Size");
const [startPrice, setStartPrice] = useState(0);
const addPizza = (e) => {
setPizzaSize(e.target.name);
setStartPrice(parseInt(e.target.value));
};
I want to use a custom button component in order to have it toggle on and off, like I have already done with other buttons on the same page.
const ButtonClickable3 = (props) => {
const [isActive, setActive] = useState("false");
const handleToggle = (e) => {
setActive(!isActive);
props.onClick(e)
};
return <button
type="button"
value={props.value}
className={isActive ? "button btn fourth" : "button btn fourthActive"}
onClick={handleToggle}
>
{props.name}
</button>
}
Finally I call the function as follows
<ButtonClickable3 name="test" value="5" onClick={(event) => addPizza(event)}></ButtonClickable3>
When I use a regular button the function works, so I am stumped as to why the custom one does not.
My custom buttons 1 and 2 are also working, but they are using a different function.
I have put my full code on a codesandbox here.
I thank you in advance for your help.
Your original <button has a name attribute, but the <ButtonClickable3 does not. so:
setPizzaSize(e.target.name);
fails with the ButtonClickable3. You need:
return <button
type="button"
name={props.name}
value={props.value}
inside ButtonClickable3.

react.js how to get prop form tree element

I am trying to make table cell editable after clicking on icon in another cell , for that I need to get index of element so the editor will open in the correct row , which icon belongs to.
My issue is that I dont know the way i should get the prop value of table DOM element here is code for for clearify
a part of dom tree generated with react:
<tbody>
{stepsDone.map(function(step,idx) {
let content = step;
const editing = this.state.editing;
if(editing){
content = (
<form onSubmit={this._save}>
<input type="text" defaultValue={step} />
</form>
);
}
return(
<tr key={idx}>
<td className="step" data-step={'step'+idx}>{content}</td>
<td className="icRow">
<Icon className="edit" onClick={this._showEditor} rownum={idx}/>
<Icon className="remove"/>
<Icon className="trash outline"/>
</td>
</tr>
)
},this)}
show editor function:
_showEditor(e){
this.setState({
editing:{
row:e.target.rownum
}
});
console.log(this.state.editing);
}
After execution of showedtior function console logs :
first click = null , which is normal i think
more clicks = undefined , and thats whats brings a trouble i want to receive idx from map function.
here is code from Icon.js
import React from 'react';
import classNames from 'classnames';
export function Icon(props) {
const cssclasses = classNames('icon', props.className);
return <i className={cssclasses} onClick={props.onClick}/>;
}
if you want to reveive the idx from the map function you should pass it to the function _showEditor so your code must be like this :
<Icon className="edit" onClick={this._showEditor(idx)}/>
and the function definition should be :
_showEditor = (idx) => (event) => {
this.setState({
editing:{
row:idx
}
});
console.log(this.state.editing);
}
or if you don't want to use the arrow functions for some reason, just replace
onClick={this._showEditor(idx)}
with
onClick={this._showEditor.bind(this,idx)}
and its definition becomes
_showEditor(idx){...}

Categories

Resources