I am making a calendar app that whenever someone clicks the input field, it should appear as a dropdown menu and in that dropwdown menu it should let me select the fields. The styles are missing for the dropdown.
This is how it should appear:
This is how it appears now:
Here is the code where I have my calendar:
import React, {useState} from 'react'
import Modal from "react-modal"
import Datetime from 'react-datetime';
function AddEvent({isOpen, onClose, onEventAdded}) {
const [title, setTitle] = useState("")
const [start, setStart] = useState(new Date())
const [end, setEnd] = useState(new Date())
const onSubmit = (e) => {
e.preventDefault()
onEventAdded({
title,
start,
end
})
onClose()
}
return (
<Modal isOpen={isOpen} onRequestClose={onClose}>
<form onSubmit={onSubmit}>
<input placeholder="Title" value={title} onChange={e => setTitle(e.target.value)} />
<div>
<label>Start Date</label>
<Datetime value={start} onChange={date => setStart(date)} />
</div>
<div>
<label>End Date</label>
<Datetime value={end} onChange={date => setEnd(date)} />
</div>
<button>Add Event</button>
</form>
</Modal>
)
}
export default AddEvent
You need to import the corresponding css for the react-datetime library for the DatePicker to have the correct style.
This should fix it:
import "react-datetime/css/react-datetime.css";
In case you run into trouble I've replicated your issue in this codesandbox where you can see it working https://codesandbox.io/s/quiet-sound-l6t6h?file=/src/Test.tsx:113-161
Additional info, it's also explained here https://www.npmjs.com/package/react-datetime (worth reading)
Related
I am using React, and I would like to find a way to trigger this message (that now triggers only when pressing the type="submit" button, on will, is there any action I can use to trigger this message at any point (for example if a user presses any other button)
<input
id="conditions"
type="checkbox"
name="conditions"
ref={acceptConditions}
required
></input>
This can be achieved with reportValidity() MDN documentation
setTimeout(() =>
document.getElementById('example').reportValidity(),
3000
)
<input id="example" type="checkbox" required />
Ok here are a few approaches, that works.
approach 1
Using the reportValidity()
This function will check the validity of the element and then trigger the event.
import { useRef } from "react";
import "./styles.css";
export default function App() {
const acceptConditions = useRef();
const formRef = useRef();
const handleSubmit = () => {
acceptConditions.current.reportValidity();
};
return (
<form ref={formRef}>
<input
id="conditions"
type="checkbox"
name="conditions"
ref={acceptConditions}
required
></input>
<span>Tick this box to continue</span>
<br />
<button type={"submit"}>submit the form</button>
<br />
<button onClick={handleSubmit}>Imposter button</button>
</form>
);
}
This is a good apporach And one that i recommend.
approach 2:
First of all if you want any other button to trigger the same event then you can do is make a reference to the form and then submit the form manually on the button press.
Here is an example.
import { useRef } from "react";
import "./styles.css";
export default function App() {
const acceptConditions = useRef();
const formRef = useRef();
const handleSubmit = () => {
console.log(formRef.current.submit);
};
return (
<form ref={formRef}>
<input
id="conditions"
type="checkbox"
name="conditions"
ref={acceptConditions}
required
></input>
<span>Tick this box to continue</span>
<br />
<button type={"submit"}>submit the form</button>
<br />
<button onClick={handleSubmit}>Imposter button</button>
</form>
);
}
in the above code the imposter button will trigger the same action as the button with the type="submit".
thank you.
It is basically rsuite#4.10.2 version
const [user, setuser] = useState('')
<InputGroup>
<Input type='text' value={user} onChange={e=>{setuser(e.target.value)}} id="user"/>
<InputGroup.Button>
<Icon icon="user" />
</InputGroup.Button>
</InputGroup>
also i have provided with the error image just look this out
enter image description here
rsuite library return the value directly in the onChange function.
So, instead:
onChange={e=>{setuser(e.target.value)}}
You should write
onChange={value=>{setuser(value)}}
This is a class that I have written with rsuite / bootstrap and basic input. You can see the difference and copy/paste the part that you want.
import React, { useState } from 'react';
import { InputGroup, Input } from 'rsuite';
import InputGroupBoostrap from 'react-bootstrap/InputGroup';
import FormControlBoostrap from 'react-bootstrap/FormControl';
const Question2 = () => {
const [user, setUser] = useState('example');
return (
<>
{/* rsuite */}
<InputGroupBoostrap>
<Input type='text' value={user} onChange={value=>{ setUser(value)}} id="user"/>
<InputGroup.Button>
Button
</InputGroup.Button>
{/* Bootstrap */}
</InputGroupBoostrap>
<InputGroupBoostrap>
<InputGroupBoostrap.Text>User 1</InputGroupBoostrap.Text>
<FormControlBoostrap value={user} onChange={(e) => { setUser(e.target.value); }} placeholder="user" />
</InputGroupBoostrap>
{/* input */}
<div>
<span>User 2</span>
<input value={user} onChange={(e) => { setUser(e.target.value); }}/>
</div>
</>
);
}
export default Question2;
I hope I've helped
import React, {useState, useEffect} from 'react'
import { NoMoralisContextProviderError } from 'react-moralis';
import './css/createpost.css'
import { useMoralis } from "react-moralis";
function CreatePost() {
const [title, setTitle] = useState("")
const [content, setContent] = useState("")
const { Moralis, isInitialized } = useMoralis();
const createNewPost = (e, title, content) => {
e.preventDefault()
const newPost = Moralis.Object.extend("Posts");
const post = new newPost();
post.set("title", title);
post.set("content", content);
post.save();
return post;
}
return (
<div>
<div>
<form action="#" className="createpost">
<div class="data">
<label>Title</label>
<input type="text" required onChange={(e) => setTitle(e.target.value)}/>
</div>
<div class="data">
<label>Content</label>
<input type="text" required onChange={(e) => setContent(e.target.value)}/>
</div>
<div class="btn">
<div class="inner"></div>
<button type="submit" onClick={createNewPost(e, title, content)}>Submit Post</button>
</div>
</form>
</div>
</div>
)
}
export default CreatePost
I’m trying to save the data to the database, but after each input change it is saved. So if I type “hello” it saves “h”, “he”, “hel”, “hell”, “hello” and I would like it to just save hello once. Not each input change. Can someone help me fix this issue?
I'm trying to save this to moralis database, but i think the error is that the function is called multiple times.
Wrap your handler to arrow function
<button type="submit" onClick={() => createNewPost(e, title, content)}>Submit Post</button>
How do I validate input box value using useRef .
Initial validation is not required once user clicks on input box and comes out then it should validate if input box is empty it should show input box cannot be empty.
Codesandbox Link
code i tried. using onBlur
export default function App() {
const name = React.useRef("");
const nameBlurData = (name) => {
console.log("name", name);
};
return (
<div className="App">
<form>
<input
onBlur={() => nameBlurData(name.current.value)}
type="text"
ref={name}
placeholder="Enter First Name"
/>
// show error message here
</form>
</div>
);
}
You can use "useRef" to validate the value of an input field.
No need to use "useState".
Below code is a basic implementation of OP's question
You can replace the "console.log" with your alert component.
import { useRef } from "react";
const ComponentA = () => {
const emailRef = useRef(null);
const passwordRef = useRef(null);
const onBlurHandler = (refInput) => {
if (refInput.current?.value === "") {
console.log(`${refInput.current.name} is empty!`);
}
}
return (
<form>
<input ref={emailRef} onBlur={onBlurHandler.bind(this, emailRef)} />
<input ref={passwordRef} onBlur={onBlurHandler.bind(this, passwordRef)} />
<form/>
)
}
Link to "useRef"
Note: Not tested, code typed directly to SO's RTE
You can use a local state and conditionally render an error message like this:
const [isValid, setIsValid] = useState(true)
const nameBlurData = (name) => {
setIsValid(!!name);
};
return (
<div className="App">
<form>
<input
onBlur={() => nameBlurData(name.current.value)}
type="text"
ref={name}
placeholder="Enter First Name"
/>
{!isValid && <span> input must not be empty </span> }
</form>
Note that you don't really need a ref in this case, you can just use the event object like:
onBlur={(event) => nameBlurData(event.target.value)}
You need to use useState hook to update the value of the name property. Using ref is not ideal here.
Live demo https://stackblitz.com/edit/react-apqj86?devtoolsheight=33&file=src/App.js
import React, { useState } from 'react';
export default function App() {
const [name, setName] = useState('');
const [hasError, setError] = useState(false);
const nameBlurData = () => {
if (name.trim() === '') {
setError(true);
return;
}
setError(false);
};
return (
<div className="App">
<form>
<input
onBlur={nameBlurData}
type="text"
value={name}
onChange={e => setName(e.target.value)}
placeholder="Enter First Name"
/>
{hasError ? <p style={{ color: 'red' }}>Name is required</p> : null}
</form>
</div>
);
}
I am trying to pass a function to a react component but it say that it is not a function. I can console log the props and I have set it up, as far as i can tell, the same way I have always done. Please help, thanks!
EDIT: I get the same error when i try to test the onSubmit function, too
<div className="bookshelf">
<Searchbar
handleChange={onChange}
addInputClass={"searchbar_mobile_input"}
addBtnClass={"searchbar_mobile_btn"}
/>
<div className="bookshelf_heading_container">
<h2 className="bookshelf__heading">
Release the Kraken of Knowledge!
</h2>
</div>
import React, {Fragment} from "react";
const SearchBar = ({ addBtnClass, addInputClass, handleChange }) => {
console.log(handleChange)
return (
<Fragment>
<form className="search__form__input" onSubmit={() => handleSubmit(e)}>
<input
type="text"
placeholder="Search by Title/Author"
className={`searchbar__input ${addInputClass}`}
name="search"
onChange={(e) => handleChange(e)}
></input>
<button type="submit" className={`btn ${addBtnClass}`}>
Search
</button>
</form>
</Fragment>
);
};
export default SearchBar;
Here is an example that should help you. You should be able to take this simplified example and work out how to apply it to your example. I would've used your code but it was incomplete and no sandbox was provided.
import React from "react";
export default function AppLogic() {
const [readValue, writeValue] = React.useState("");
const handleChange = (e) => writeValue(e.target.value);
const handleSubmit = (e) => {
e.preventDefault();
alert("Submitted");
};
const props = { readValue, handleChange, handleSubmit };
return <AppView {...props} />;
}
function AppView({ handleSubmit, handleChange, readValue }) {
return (
<div className="App">
<h1>Name</h1>
<form onSubmit={handleSubmit}>
<input onChange={handleChange} value={readValue} />
<input type="submit" />
</form>
<p>{readValue}</p>
</div>
);
}