How to condition a component to display certain information? - reactjs

const handleChecked=(e)=>{
setForm({
...form,
[e.target.name]:e.target.checked
})
if(e.target.name == 'lowercase'){
showMinus(longitud)
}
}
const handleSubmit =(e)=> {
updatePassword(longitud)
activeLetters()
e.preventDefault();
}
file 1
const ShowPass =()=>{
let charactersLength = characters.length;
let allChar = ''
for(let i = 0; i<range.current.value; i++){
allChar += characters.charAt(Math.floor(Math.random()* charactersLength))
}
setPassword(allChar)
}
const showMinus=(minusculas)=>{
let allMin=''
let minLong = minusculas.length;
for(let i = 0; i<range.current.value; i++){
allMin += minusculas.charAt(Math.floor(Math.random()* minLong))
}
setMinus(allMin)
}
//¿Que tipo de carcarter es?
const activeLetters =()=>{
let min = ''
for(let i=0;i<characters.length;i++){
let element = characters[i];
if(element === element.toLowerCase() && element !== element.toUpperCase())
min+=element
}
showMinus(min)
}
useEffect(()=>{
getPassLength()
},[])
return(
<>
<div className='classHeader'>
<ShowPassword password={password} icon={<HiOutlineClipboardList/>} />
</div>
<div className='longBox'>
<p>Character Length</p>
<input type="range" min={1} max={16} step={1} ref={range} name="password" ></input>
{long}
</div>
<CapitalLetters
updatePassword={ShowPass}
showMinus={showMinus}
activeLetters={activeLetters}
longitud={long} />
</>
)
Hello everyone, I would like your help please: I am in a situation with the code, what I want to do is the following:
It is a password generator when I give it send
this generates a random password for me when I click the submit button, for this I have created an external component called showPassword that receives a prop called password So, so far so good because I manage to do that, my problem comes in the form file because I have some checkboxes, I want that when push lowercase it sends the password to the screen in only lowercase, that's where my problem is I don't know how to do it,
how do you think i should do it?

So on checkbox click use a state to see whether the ckeckbox is clicked on not. If yes there are js function to convert string to lowercase.
The toLowerCase() method converts a string to lower case letters.

Create a state that will control whether the checkbox is checked or not then inside the props you can create a ternary operator that will send a lowercase if checked or a normal password if not.
<ShowPassword password={isChecked ? password.toLowerCase() : password} icon={<HiOutlineClipboardList/>} />
Hope this works!

Related

React controlled <type='number'> input allows typing in letter?

I am writing an app that contains a controlled input that has the type 'number'. I can still type letters in the input field, but the e.target.value just gets emptied. Does anyone know how I can disable the typing of letters? Namely, if a user types in a letter, the input field will simply not register but still keeps the numbers previously typed in.
Here is my code:
export class AddNewRecipe extends React.Component {
constructor(props){
super(props);
this.state={prepField:{numeral:""}};
this.handleInput = this.handleInput.bind(this)}
handleInput(e){
e.preventDefault();
if(e.target.className =='prepNumber')
{
console.log(e.target.value)
const newPrep = Object.assign({}, this.state.prepField)
newPrep.numeral = currentValue
this.setState({prepField: newPrep})
}
render(){
return (<PrepTime
handlePrep={this.handleInput}
prepField={this.state.prepField}
/>
)
}
and here is the child component
export default function(props){
return(
<div id = 'prepForm'>
<input id = 'prepFormInput' type='number' className='prepNumber' value={props.prepField.numeral} onChange={props.handlePrep} placeholder='prep time' />
</div>
)
}
Does anyone know why that is? Because if I accidentally type '10v', the e.target.value which I will set to my state 'prepField.numeral' just becomes emptied.
Thank you!
You can use this code:
<input id = 'prepFormInput' type='number' className='prepNumber' value={props.prepField.numeral} onChange={props.handlePrep} placeholder='prep time' onkeydown="javascript: return ['Backspace','Delete','ArrowLeft','ArrowRight'].includes(event.code) ? true : !isNaN(Number(event.key)) && event.code!=='Space'" />
This will avoids all characters that are not numbers!
This part make's input accept only numbers:
!isNaN(Number(event.key))
This part make's accept the arrow and delete keys:
['Backspace','Delete','ArrowLeft','ArrowRight'].includes(event.code)
This part make's Firefox disallow spaces in numbers:
event.code!=='Space'
(For react Applications)
If someone has text input and wants to accept only whole numbers. You can use the following code.
const numberInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
const eventCode = event.code.toLowerCase();
if (!(event.code !== null
&& (eventCode.includes("digit")
|| eventCode.includes("arrow")
|| eventCode.includes("home")
|| eventCode.includes("end")
|| eventCode.includes("backspace")
|| (eventCode.includes("numpad") && eventCode.length === 7)))
) {
event.preventDefault();
}
};
I have compared the length of eventCode to 7 when it includes numpad because its actual value is like numpad0, numpad1 ... numpad9
This function can be specified in onKeyDown such as
<input
id="myNumberInput"
type="text"
placeholder="numeric input"
onKeyDown={numberInputKeyDown}
/>
To extent field to accept decimals or negative numbers you can console.log the eventCode in numberInputKeyDown to check your required key code and add it in if statement.

React function in displaying returned value not working

I am trying to display calculated values from a function called renderAnalysis - all which works until the bottom of the function where I am trying to return a div with the values that are found. However, this isn't displaying (all values are returned though in the console when I test it out) and was wondering what I need to adjust to prevent the values I can show in the console? I think I'm doing a render call wrong or something... I've added the code for reference. Thank you!
renderAnalysis = () => {
let reactions = this.state.reactions;
let foods = Object.keys(reactions);
foods.map((food) => {
let reactionDescriptions = reactions[food];
let reactionDescriptionKeys = Object.keys(reactionDescriptions);
let responseKey = Object.keys(reactionDescriptions);
responseKey.map((singleDescription) => {
let value = reactionDescriptions[singleDescription];
// RETURN VALUE NOT SHOWING
return <div> {(food, singleDescription, value)} </div>;
});
});
};
Further information: There is a toggle I made in state that if someone clicks a button it triggers this function. Basically
<button onClick={this.displayRenderAnalysisToggle}>
Render Analysis
</button>{" "}
<br />
{this.state.displayRenderAnalysisToggle ? this.renderAnalysis() : null}
</div>

How do I autosubmit text after entry?

I was wondering what's the best approach for handling an autosubmit of a code that a user types in? I have this so far but idk if this works. I tried testing it but I wasn't performing as I expected.
This is the form control:
<div className="form-group">
<input
type="tel"
autoComplete="one-time-code"
maxLength="6"
className="code-form"
onChange={this.changeCode}
value={code}
/>
</div>
And this is the onChange event:
changeCode = e => {
this.setState({ code: e.target.value });
if(this.verificationCode.length == 6) {
this.verifyCode();
}
};
If the length of what the user types in is 6, then I just want to submit it. Is this right approach?
The following code is inside a webview react project that is housed inside of react-native app.
There is no need to use debouncing for such small task,just check lenght of code in setState's call back and submit.
changeCode = e => {
this.setState({ code: e.target.value },()=>{
if(this.state.code.length == 6) {
this.verifyCode();
}
});
};
You can try with throttle and debounce:
if (this.verificationCode.length < 5) {
throttle(500, this.verifyCode)
} else {
debounce(500, this.verifyCode);
}

How can I set customvalidity to have a Link in it?

I have a customvalidity function for when a username or email are taken, and I want to give the user the option to go to signin from there. Is this possible?
I have tried creating an object for the Link object, from react-router dom, but it eiter doesn't come up when added with a comma, or comes back object object when inserted with a plus sign. I want the email taken notification to have the link in it so the user can click on login directly.
handleSubmit = async (e) => {
e.preventDefault();
const EmailField = document.getElementById('email');
const userField = document.getElementById('username');
const signinRedirect = <Link to='/signin'> login </Link>;
const newUser = {
username : this.state.username,
email : this.state.email,
password : this.state.password,
confirmPassword : this.state.confirmPassword,
};
//check passwords match before submitting
if (this.state.passwordsMatch) {
let url = window.location.hostname.split('.')[0] === 'localhost' ? 'http://localhost:3306' : 'https://petsosbackend.apps.nonprod-mpn.ro11.allstate.com';
try {
await axios.post(url + '/register', newUser)
.then(res=> {
if (res.status===202) {
this.props.history.push('/registersuccess');
//if email is taken
} else if (res.data==='email'){
EmailField.setCustomValidity('Email address is in use, please select another or '+ {signinRedirect});
EmailField.reportValidity();
//if name is taken
} else if (res.data==='name') {
userField.setCustomValidity('Username is in use, please select another or' + signinRedirect);
userField.reportValidity();
}
})
} catch(error) {
console.log("Catch = ", error.response);
}
}
}
There is more logic obviously but think these are the two key parts and just need help figuring out how to have the signinRedirect appear in the validity warning.
Thanks a lot!
Principle:
return (
<div className="form-control">
<input type="text" name="email" value={email} onChange={handleChange} />
{isEmailInUse && (
<div className="error">
Email address is in use, please select another or <Link to='/signin'>Sign in</Link>
</div>
)}
</div>
);
You are trying to use native messages in a JSX validation method. So you can not do.
JSX has nothing to do with HTML, besides being a way of describing the structure of a document and a similar syntax.
JSX In Depth
Just do not use native error reporting. Use your own solutions, like the ones I gave in the answer.
You are also working incorrectly with DOM elements. In React, it is common practice to use Ref API or monitored components.
And whenever possible, there should be no conditions in the code like:
window.location.hostname.split('.')[0] === 'localhost'
For such tasks there are env variables and configurations. You can set BASE_URL and use different values for different modes.

Input validation using pattern attribute in reactjs

i am new to reactjs. I want to validate the input element with pattern attribute (can accept atleast one character) in reactjs. Below is what i have tried doing.
handle_text_input_change = (event) => {
this.props.onChange(event);
console.log("handle",event.target.name);
this.setState({text_input_value: event.target.value});
this.validate(event);
};
validate = (event) => {
let name = event.target.name;
console.log("target name", name);
//const target = event.target;
if (event.target.ValidityState.patternMismatch) {
this.setState({is_valid: false});
this.setState({error: 'Enter the'+ {name} +'with atleast one
character'});
}};
return (
<div>
<input {...rest}
type="text"
onChange={this.handle_text_input_change}
disabled={disabled}
onBlur={this.handle_blur}
onFocus={this.handle_focus}
pattern=".+"
/>
{(valid && active)&& <span className="error">Enter a name</span>}
</div>
);
So this will display the error message when input invalid. However, in the validate method i am checking if input value not null then consider valid. But how can i do input validation using pattern attribute and display error message similarly. Thanks.
Edited: I have tried using html5 validation api as in above code. but then i get the error "Uncaught TypeError: Cannot read property 'valueMissing' of undefined". could someone help me with this. thanks.
You haven't added a value property on your input:
<input {...rest}
type="text"
onChange={this.handle_text_input_change}
disabled={disabled}
onBlur={this.handle_blur}
onFocus={this.handle_focus}
value={this.state.text_input_value}
/>

Resources