react set value to a textfield - javascript

everytime the closeEmail is triggered or called I wanted to assign the email.emailAddress as the value of the textfield.
just really new to react , what is the syntax or way to do this ?
Any idea guys ?
#code snippet
<div style={{ display: "block" }}>
<FormControl sx={{ mt: 2, minWidth: 720 }}>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<TextField
style={{ width: "95%" }}
onChange={emailOnChange}
label="Email Address"
variant="filled"
name={email.emailAddress}
defaultValue={email.emailAddress}
/>
<DeleteIcon style={{ color: "red" }} onClick={() => deleteEmail(email, prop.id)} />
</div>
#ts
const closeEmail = (email: IEmail) => {
const test = email.emailAddress;
setOpenEmail(false);
return email.emailAddress;
}

Firstly, you have to create the state for the TextField to set the value
you can achieve with the following changes
import at the top:-
import React,{useState} from 'react';
then create state :-
const[emailValue, setEmailValue] = useState('');
on your function call closeEmail()
const closeEmail = (email: IEmail)=>{
count test = email.emailAddress;
//add
console.log("test",test);
setOpenEmail(false);
return email.emailAddress;
}
Add console to check first you are getting the desired value that you want to set to TextField.
if the value you getting is correct then set the state
const closeEmail = (email: IEmail) => {
const test = email.emailAddress;
//add
console.log("test",test);
//add
setEmailValue(test);
setOpenEmail(false);
return email.emailAddress;
}
Adding this setEmailValue(test) will set state,
now you can access by using 'emailValue'
add the following
<TextField
value={emailValue}
style={{ width: "95%" }}
onChange={emailOnChange}
label="Email Address"
variant="filled"
/>
This is how you can set the email.emailAddress value to TextField

Basically, if you want to control the value of your TextInput you should pass value prop to your TextInput.
<TextField
style={{ width: "95%" }}
value={email.emailAddress}
label="Email Address"
variant="filled"
name={email.emailAddress}
defaultValue={email.emailAddress}
onChange={emailOnChange}
/>
You can have controlled or uncontrolled components:
A Controlled Component is one that takes its current value through
props and notifies changes through callbacks like onChange. A parent
component "controls" it by handling the callback and managing its
own state and passing the new values as props to the controlled
component. You could also call this a "dumb component". A
Uncontrolled Component is one that stores its own state internally,
and you query the DOM using a ref to find its current value when you
need it. This is a bit more like traditional HTML.

you need to pass value of textField like this,
<TextField
value={email.emailAddress}
...
/>

Related

parent component won't show up if I don't pass all the props to the child

First of all, it's good to mention that I'm a bit new to react world. I am using Mui with react. here is my code:
const Search = (props) => {
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("sm"));
return !isSmall || props.show ? <SearchDiv {...props} /> : null;
};
as you can see it's a simple component that under a circumstance returns another custom component. my problem is that if I Don't add {...props} to the child component(SearchDiv) the whole component Search won't show up. but if I add everything works fine and I can't understand why? do we always need to pass all props to any child component?
I searched StackOverflow and google but I didn't find something similar to my question.
Edit : here is the rest of the code:
const SearchDiv = styled("div")(({ theme }) => ({
position: "relative",
borderRadius: theme.shape.borderRadius,
backgroundColor: alpha(theme.palette.common.white, 0.15),
"&:hover": {
backgroundColor: alpha(theme.palette.common.white, 0.25),
},
marginLeft: 0,
width: "50%",
[theme.breakpoints.up("sm")]: {
marginLeft: theme.spacing(1),
},
[theme.breakpoints.down("sm")]: {
marginLeft: theme.spacing(1),
},
}));
const Navbar = () => {
const [showSearch, setShowSearch] = useState(false);
return (
<AppBar>
<Toolbar sx={{ display: "flex", justifyContent: "space-between" }}>
<Search show={showSearch}>
<StyledInputBase
placeholder="Search…"
inputProps={{ "aria-label": "search" }}
/>
</Search>
<SearchIcon onClick={() => setShowSearch(true)} />
</Toolbar>
</AppBar>
);
};
export default Navbar;
For reference, see Composition vs Inheritance.
Without passing props, ie
<SearchDiv />
your styled <div> has no children to render. When you pass all the parent props via {...props}, that includes children, the equivalent of...
<SearchDiv children={props.children} show={props.show} />
I wouldn't recommend this though. An alternative would be
<SearchDiv>
{ props.children }
</SearchDiv>
as per the containment section of the guide linked above.

How to change the focus of text input when using custom text input

1.Here is my custom text input custom component i define props ref which i want to use in
parent component
export const InputField = ({
placeholder,
onChangeText,
placeholderTextColor,
showSecureIcon,
isSecure,
onPressIcon,
keyboardType,
returnKeyType,
maxLength,
secureIconColor,
handleUseCallBack,
ref,
value
}) => {
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder={placeholder}
onChangeText={onChangeText}
placeholderTextColor={placeholderTextColor}
autoCapitalize="none"
secureTextEntry={isSecure}
keyboardType={keyboardType}
returnKeyType={returnKeyType}
maxLength={maxLength}
value={value}
ref={ref}
/>
<View style={styles.iconContainer}>
{showSecureIcon ?
<TouchableOpacity
onPress={onPressIcon}
>
<Ionicons
name={isSecure ? "eye-off-sharp" : "eye-sharp"}
color={secureIconColor}
size={constants.vw(25)}
/>
</TouchableOpacity>
:
null
}
</View>
</View>
)
}
2-Now the part where i want to change my ref
in this field i create the text inputs field of password and confirm where i want to change
my focus
const passwordRef = useRef(null);
const confirmPasswordRef =
useRef(null);
const onSubmitEditing=()=>{
confirmPasswordRef.current.focus();
}
<View style={{ marginTop: constants.vh(66) }}>
<Components.InputField
placeholder={constants.ConstStrings.setANewPassword}
ref={passwordRef}
onSubmitEditing={()=>onSubmitEditing()}
onChangeText={(text) => setState({
...state,
password: text
})}
/>
</View>
<View style={{ marginTop: constants.vh(20) }}>
<Components.InputField
ref={confirmPasswordRef}
placeholder={constants.ConstStrings.confirmPassword}
onChangeText={(text) => setState({
...state,
confirm_password: text
})}
/>
</View>
This part is the end part qwertyuiopsdf;';dsyuiopoiuteweryuiopuytreep[gfjklvcvbnm,mvcxzxcewqwe[poiuyd
The problem with your code is that you've created a custom input component, but haven't given to it the instructions on how to handle different methods.
So, in your case, the generic Input component knows what method is focus, but your custom one doesn't.
What you should do:
Make your input component a forwardRef one so that you can pass a ref to it and then be able to do actions on it.
Use useImperativeHandle so that you can call internal methods of your ref.
Create a focus fn which in your custom input will basically call the focus method of your ref.
You cannot pass the ref in props as you are doing, that just doesn't work in React.
I suppose all of your components are functional, in that case:
export const InputField = React.forwardRef({
placeholder,
...
}, ref) => { // pass a ref to here, this way you will let React know to associate the ref from external component to an internal ref
const textInput = useRef(null); // Create a ref to pass to your input
useImperativeHandle(ref, () => ({ // To be able to call `focus` from outside using ref
focus,
});
const focus = textInput.current.focus();
return (
<View style={styles.container}>
<TextInput
ref={textInput}
style={styles.input}
...
/>
...
</View>
)
}
And then in your component you just have to pass a fresh ref created by useRef and then you'll be able to call focus on in.
Tell me whether that solves it for you!

How change the value of a Switch in a Formik form?

do you know how to change the value of a Switch in a Formik form?
It's not working like other fields like Text Input or picker.
<Picker onValueChange={handleChange('type')} selectedValue={values.type} style={{ height: hp('3%'), width: wp('30%') }} >...
<TextInput onChangeText={handleChange('title')} onBlur={handleBlur('title')}...
I have tried many differents ways and followed a response in StackOverflow but my code does not know the "set Field Value" function
<Switch onValueChange={ value => setFieldValue('hidden', value)} value={values.hidden} style={{ marginTop: hp('-0.5%') }}></Switch>
Formik using React Native Switch
This the initial values of thr form:
initialValues={{
title: '',
type: 'Text',
hidden: false,
order: '0',
graphicType: 'Camembert'
}}
Coudl you pleasse help me ?
Check my custom component using useFormikContext, notice that the value is equal to values[name]
function SwitchInput({ name, icon, width = "100%", placeholder }) {
const { setFieldValue, values, errors, touched } = useFormikContext();
return (
<View>
<Switch
trackColor={{ false: "#767577", true: "#81b0ff" }}
thumbColor={values[name] ? "#f5dd4b" : "#f4f3f4"}
ios_backgroundColor="#3e3e3e"
onValueChange={(value) => setFieldValue(name, value)}
value={values[name]}
/>
<ErrorMessage error={errors[name]} visible={touched[name]} />
</View>
);
}

React js - how to assign result of a function to a state?

I have a question about react
currently in my app I want to get some data from server, and set default value of input, all of pulling is done in a function, but when I'm trying set state equal to function looks like react is thinking that I'm assigning function to state as a result on every input change state is being updated with function ignoring actual typing, is there a way to get past this?
Here is code for render part of component:
{metaList["properties"] &&
metaList["properties"].map((item, idx) => (
<label key={idx} style={{ display: "block", marginBottom: "20px" }}>
{item.name + ":"}
<div style={{ display: "none" }}>
{this.findMeta()
? (this.state.properties[item.name] = this.findMeta())
: ""}
{this.state.properties[item.name]
? this.state.properties[item.name]
: (this.state.properties[item.name] = "")}
</div>
<input
name={item.name}
placeholder={item.name}
value={this.state.properties[item.name]}
onChange={this.handleInputChangeProperties}
style={{
marginLeft: "20px"
}}
/>
</label>
))
}
this.findMeta is function I'm trying to call, nothing is special in it, function returns one variable as a string to get field filled.

Set up React Native children component

I trying to send data trough the props from parent component to children in React Native.
Parent Component
<Card>
<CardSection>
<Input
proportion={5}
label="Email"
/>
</CardSection>
<CardSection>
<Input
proportion={3}
label="Password"
/>
</CardSection>
</Card>
Children Component
const Input = ({ proportion, label }) => {
const { inputStyle } = styles;
inputStyle.flex = proportion;
return (
<View style={containerStyle}>
<Text>{label}</Text>
<TextInput style={inputStyle} />
</View>
);
};
const style = {
inputStyle: {
flex: 2
}
};
And I've got error You attempted set the key 'flex' with the value '3' on an object that is meant to be immutable and has been frozen. Interesting fact, when I've one <Input /> Component everything works fine and set flex: 5, and I reach what I wanted, but with second <Input /> Component I've got error. How I can fix this and set properly?
I think that the good way is to use object spread operator:
const Input = ({ proportion, label }) => {
const { inputStyle } = styles;
return (
<View style={containerStyle}>
<Text>{label}</Text>
<TextInput style={{...inputStyle, flex: proportion}} />
</View>
);
};
const style = {
inputStyle: {
flex: 2
}
};
You define style like const, so you get an error. You can also define it like variable by let.

Categories

Resources