ReactJS // SearchBar onClick button - javascript

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>

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>

React component not sending variable value with onChange event

I am trying to display more than one task using the same react component and a map function. The components is supposed to upload a file and display the file that has been upload or is uploading with an onChange event, an onSubmit event will be added later to send the file to the back-end. Since the component is being dynamically rendered with an onChange event I am sending the li key as a parameter then only rendering the filename to the li that matches based on the key. The issue I am currently having is when I send the key in the onChange the value is not getting to the function. I have even tried setting a state for the key and then pulling that into the function but I get back undefined I have tried 100 other things as well and either get back undefined or 0. This is my first post on here and I am also just a junior dev so I may be missing info needed here if so please let me know.
Here is the code
const onChange = (e, index) => {
setFilename(e.target.files[0].name)
setArrFiles([...arrFiles, {key:index, file:e.target.files[0].name} ])
}
const displayTask = (index) => {
let upload = []
arrFiles.forEach(el => {
if(el.key === index) {
upload.push(el.file)
}
})
return upload.map((file) => (
<li key={index}>{file}</li>
))
}
{database.map((task, index) => (
<li key={index}>
<p>{index}</p>
<div className="userPortal__tasksContainer">
<div className='userPortal__tasksHeader'>
<p className='userPortal__tasksHeaderTitle'>{task.taskTitle}</p>
<p className='userPortal__tasksHeaderInfo'>{task.taskMessage}</p>
</div>
<div className='userPortal__tasksBodyButtons'>
<form className='userPortal__fileUpload'>
<input className='userPortal__inputButton' multiple id='file' type="file" onChange={e => onChange(e, index)}/>
<label htmlFor='file'>Choose File</label>
</form>
<button className='userPortal__tasksBodyButton green'>Task Complete</button>
</div>
<p id='userPortalFooterTitle'>Successfully Uploaded</p>
<div className='userPortal__footer'>
<ul>
{displayTask(index)}
</ul>
</div>
</div>
</li>
))}
The issue here was like a dummy I hard coded the input ID so when referencing the input field it would only get the hard coded value instead of the index of the component.
Here is the updated form.
<form className='userPortal__fileUpload'>
<input className='userPortal__inputButton' multiple id={index} type="file" onChange={(() => (e) => onChange(e, index))()}/>
<label htmlFor={index}>Choose File</label>
</form>
No Do It Like This
const onChange = (e, index) => {
setFilename(e.target.files[0].name);
// Okay You Need To Filter The State In Order To Get The Object With THe Current Index
// Set The File Value Of The Object To e.target.files[0].name
setArrFiles((state) => {
const allFiles = state;
const currentFile = allFiles.filter(
(file) => parseInt(file.key) === parseInt(index)
)[0];
// i converted it to an integer just to prevent further bugs
currentFile.file = e.target.files[0].name;
return [allFiles];
});
};

Bring Properties to the button in React js

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.

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.

Categories

Resources