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>
Related
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>
I noticed today that while using a custom onChange in a Form.Control that the text in the field no longer changes when a file is selected. I have looked through the documentation on the Git HERE but it doesnt say how to change the text with a custom event.
my code:
// handles when a file has been selected.
const handleUploadChange = (event) =>
{
setFileToUpload(event.target.files[0]);
setIsFilePicked(true);
}
// Footer containing buttons and file selection
const CardFooter = () =>{
return(
<Card.Footer>
<div style={{width:"80%", display : "flex", flexDirection: "row", justifyContent: "center"}}>
<div style={{marginRight: "40px"}}>
<Form.Group controlId="formFile" className="mb-3">
<Form.Control type="file" custom onChange={handleUploadChange} label={fileToUpload === null ? "No File Selected" : fileToUpload.name}/>
</Form.Group>
</div>
<div className="btn-red" style={{marginRight: "40px"}}>
<Button disabled={fileToUpload === null} onClick={()=>{setFileToUpload(null); setIsFilePicked(false);}}>Clear</Button>
</div>
<div>
<Button disabled={(fileToUpload === null) || (fileToUpload.size >= maxUploadSizeInBytes)} onClick={()=>handleSubmit(fileToUpload)}>Upload</Button>
</div>
</div>
</Card.Footer>
)
}
As you can see here, once a file is selected, my change event happens, but the selection box still reads "No file chosen". I have attempted label, text, displayName , and placeholder like so: label={fileToUpload === null ? "No File Selected" : fileToUpload.name}
Does anyone know the proper prop to use with a custom onChange ?
You can't control input of type "file" in React. When you choose a file, the text/"label" should automatically be updated. You don't have to manage it. Just set the state on select and read the state on submission. To fix your clear button, you could use useRef:
const fileInputRef = useRef(null);
...
<Form.Control ref={fileInputRef} ...>
...
<Button onClick={() => {
setFileToUpload(null);
fileInputRef.current.value = null;
}}>
Clear
</Button
Also consider following:
You don't need your "isFilePicked" state. It can be derived from "fileToUpload" with Boolean(fileToUpload).
There is no Form.Control custom property.
Nore there is a Form.Control label property. If you need a label, add Form.Label to it. You can hide the file input and style your own input solution if you want to.
Codesandbox:
https://codesandbox.io/s/beautiful-vaughan-zn68t
Read more:
how to hold file input value in react
How to reset ReactJS file input
I am working on a tasklist page. The main page has a form in which the user would add the task and click on the add task button and the corresponding task would be appended to the "todo-task" div. I am using my own created react element (Do laundry is just for example) which returns a checkbox followed by the text passed as prop. In the following code I am trying to append at the end of our todo-task div but it is showing me some error. Is my approach right? If not what approach should I take?
import React,{useState} from 'react'
import './Tasklist.css'
import Button from 'react-bootstrap/Button';
import AddBoxIcon from '#material-ui/icons/AddBox';
import Checkbox from '#material-ui/core/Checkbox';
import Task from './Task.js';
function Tasklist() {
const [task, settask] = useState("")
let pendingTask = document.getElementById('pending-task')
let doneTask = document.getElementById('done-task')
const addTask = (event)=>{
event.preventDefault()
let tmp_text=task.trim()
if(tmp_text==="")return
let task_tmp = document.createElement(<Task text={tmp_text} />);
pendingTask.appendChild(task_tmp);
settask("");
}
const keyDownEvent=(e)=>{
let key=e.key
if(key==='Enter' && !e.shiftKey)addTask(e);
}
return (
<>
<div className="add-task">
<form >
<textarea
type="text"
value={task}
rows={1}
placeholder="Add Task"
onChange={(e)=>settask(e.target.value)}
onKeyDown={keyDownEvent}
/>
<Button variant="outline-primary" onClick={addTask}>
<AddBoxIcon /> Add Task
</Button>
</form>
</div>
<div className="todo-task" id="pending-task">
</div>
<Task text="Enjjoyyyy!!!" />
<hr />
<div className="done-task" id = "done-task">
<ul id="done-task-list">
</ul>
</div>
</>
)
}
export default Tasklist
You're going about this in a fundamentally incorrect way, so it's not a quick fix. Now is the time to take a big step back and start over on your component.
What you're currently trying to do is modify the DOM directly. Don't do that in React. What you should instead be doing is maintaining state.
Instead of trying to directly create an element and add it to the DOM, create a record and update state with that record. This is an entirely separate task than rendering the DOM. The actual rendering is done based on that current state.
Currently in your state you have "a task". But you're trying to build functionality to add more tasks. So really your state should have a list of tasks, and you can add to that list. (Which can be in addition to the single task, of course. You can use useState as many times as you like.)
For example, consider state like this:
const [tasks, setTasks] = useState([]);
Then add a task in your button click handler:
const addTask = (event)=>{
event.preventDefault();
let tmp_text=task.trim();
if(tmp_text==="") return;
setTasks([...tasks, tmp_task]); // <--- here
settask("");
}
This keeps a running array of the tasks being stored.
Then in the rendering, you would .map over those tasks to show them:
<div className="todo-task" id="pending-task">
{tasks.map((t, i) => (
<Task key={i} text={t} />
))}
</div>
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.
I am using react. I want to add a line break <br> between strings
'No results' and 'Please try another search term.'.
I have tried 'No results.<br>Please try another search term.'
but it does not work, I need to add the <br> in the html.
Any ideas how to solve it?
render() {
let data = this.props.data;
let isLoading = this.props.isLoading;
let isDataEmpty = Object.entries(data).length === 0;
let movieList = isLoading ? <Loader /> : isDataEmpty ? 'No results. Please try another search term.' :
Object.entries(data).map((movie, index) => <MovieTile key={index} {...movie[1]} />);
return (
<div className='movieList'>{movieList}</div>
);
}
You should use JSX instead of string:
<div>No results.<br />Please try another search term.</div>
Because each jsx should have 1 wrapper I added a <div> wrapper for the string.
Here it is in your code:
render() {
let data = this.props.data;
let isLoading = this.props.isLoading;
let isDataEmpty = Object.entries(data).length === 0;
let movieList = isLoading ? <Loader /> : isDataEmpty ? <div>No results.<br />Please try another search term.</div> :
Object.entries(data).map((movie, index) => <MovieTile key={index} {...movie[1]} />);
return (
<div className='movieList'>{movieList}</div>
);
}
You can use CSS white-space to solve the problem.
React Component
render() {
message = `No results. \n Please try another search term.`;
return (
<div className='new-line'>{message}</div>
);
}
CSS
.new-line {
white-space: pre-line;
}
OUTPUT
No results.
Please try another search term.
break text to line:
render() {
...
<div>
{this.props.data.split('\n').map( (it, i) => <div key={'x'+i}>{it}</div> )}
</div>
...
Some HTML elements such as <img> and <input> use only one tag. Such tags that belong to a single-tag element aren't an opening tag nor a closing tag. Those are self-closing tags.
In JSX, one has to include the slash. So, remove <br> and try <br />
Here is how I got around this. Let message be the prop/variable that has the string containing line breaks to be displayed in HTML as follows:
message = 'No results.<br>Please try another search term.';
<div>
{message}
</div>
To make this work, we need to use \n instead of break tag <br> and set the following css on the wrapper element of this message as follows:
message = 'No results.\nPlease try another search term.';
<div className="msg-wrapper">
{message}
</div>
CSS:
.msg-wrapper {
white-space: pre-wrap;
}
OUTPUT:
No results.
Please try another search term.
If you don't want put the string inside a <div> you could use <> to do it.
Like this:
var text = <>This is a text in the first line;<br />this is a text in a second line</>;
Just split text by /n, I do this in this way:
<div>
{text.split('\n').map((item, i) => <p key={i}>{item}</p>)}
</div>
Try with span
return (
<div className='movieList'><span>{movieList}</span></div>
);
If you are like in my situation and you don't want to add css, you can do that :
render () {
...
return (
...
<Typography component="p">
...
{(contact.lastname)?<div>Hello {contact.firstname} {contact.lastname}</div>:''}
...
</Typography>
...
);
}
using ` worked for me however i am not sure if it is the exact solution to the problem :
import React from 'react';
import ReactDOM from 'react-dom';
let element = (
<div>
<h1> Hello world</h1>
This is just a sentence <br></br>
But This line should not be in the same previous line. <br></br>
The above content proves its working. <br></br>
npm v6.14.6 | react : {React.version}
</div>
);
ReactDOM.render(element,document.getElementById("html-element-id"))
You can add a span tag and add block as a class.
Pomodoro Technique Timer <span className="block">with Bla</span>
The simplest thing which I did is by creating a component.
const EmptySpace = ({ spaceCount = 0 }) => {
return (
<>
{Array.from({ length: spaceCount }, (item, index) => {
return <br key={index} />;
})}
</>
);
};
export default EmptySpace;
<EmptySpace spaceCount={1} />
In your case you could do something like this:
const msg = (
<p>
No results <EmptySpace spaceCount={2} />
Please try another search term.
</p>
);