I am trying to adjust the width of a view and color according to a variable. I initially declare the variable inside the app which doesnt seem to work. I have also tried declaring the variable outside the function scope but doesnt register. Is there anyway I could dynamically edit the width of the child using the declared variable? Or is there a function that allows me to do this?
const app = () =>{
const childWidth = 50;
const viewColor = 'red'
return(
<View style={styles.parent}>
<View style={styles.child}>CHILD</View>
</View>
)}
styles = styleSheet.create({
parent:{
width: 100,
color: 'white',
},
child:{
width: {childWidth},
color: {viewColor},
}
})
Thanks in advance
CodePudding user response:
i suggest you can use styles in condition
const app = () =>{
const isChildOneStyle = true
return(
<View style={styles.parent}>
<View style={isChildOneStyle ? styles.child1 : styles.child2}>CHILD</View>
</View>
)}
styles = styleSheet.create({
parent:{
width: 100,
color: 'white',
},
child1:{
width: 50,
color: 'red',
},
child2:{
width: 80,
color: 'green',
},
})
or you can overrite style
const app = ({customStyles}) =>{
return(
<View style={styles.parent}>
<View style={[styles.child, customStyles]}>CHILD</View>
</View>
)}
or if you retreived this parameters from api you can do like this
const app = ({customWidth, customColor}) =>{
return(
<View style={styles.parent}>
<View style={[styles.child, { width :customWidth , color: customColor }]}>CHILD</View>
</View>
)}
CodePudding user response:
I am assuming you want to edit the width dynamically so let's change it using an InputText.
first let's create our useState hook.
const myFunc = () =>{
const [width , setWidth] = useState("50px")
return(
<>
<TextInput onChangeText={setWidth}
value={width} />
//let's assume you want to change the width of this element.
<element style={{width : {width} }}
</>
)
export default ...