How to change text Value upon Button press in React Native?
You could use a state to keep your default text and then on press we update the state.
import React, { Component } from 'react'
import { View, Text, Button } from 'react-native'
export default class App extends Component {
state = {
textValue: 'Change me'
}
onPress = () => {
this.setState({
textValue: 'THE NEW TEXT GOES HERE'
})
}
render() {
return (
<View style={{paddingTop: 25}}>
<Text>{this.state.textValue}</Text>
<Button title="Change Text" onPress={this.onPress} />
</View>
)
}
}
Change a text value after pressing a button
I don't know if i understood your question, but, if you want to change a variable value, by pressing a button, you first have to put the variable in the "memory of the screen" that is, in the state, like you did in:
const [altura, setAltura] = useState('');
So you should do something like this
const [imc, setIMC] = useState(0);
And after, create a function that calculates the IMC, I recomend you always use arrow function because it prevents some bugs in the future.
const CalculateIMC = () => {
let imc = peso / (altura*altura/10000); // I used "let" instead of "var" because "let" only exists inside this function so it uses less memory. Think about largers aplications
setIMC(imc); // Here you are setting the variable imc in the memory of yout screen
// After this you can use your logic to determinates in what category the user is.
}
After that you can delete this line
var imc = peso / (altura * altura / 10000)
Change Button Text in loop using React
In the below snippet I've implemented an example, just for keep it simple, I've used static data as list. I hope it could help.
const data = [{ "name": "lorem ipsum", "description": "description1", "company_name": "PT dapibus ", "company_slug": "pt-dapibus", "watchlist": true, "id": 1 },{ "name": "lorem ipsum2", "description": "description2", "company_name": "Google", "company_slug": "company_slug", "watchlist": true, "id": 2 }]
function RenderFeeds({ feeds, onAddToWatch, onRemoveFromWatch }) {
return (
<React.Fragment>{/* or any markup you want */}
{feeds.map((feed) => (
<div className="feed" key={feed.id}>
<h1>{feed.name}</h1>
<h2>{feed.company_name}</h2>
<h2>{feed.description}</h2>
<button
onClick={() =>
feed.watchlist
? onRemoveFromWatch(feed.id)
: onAddToWatch(feed.id)
}
>
{feed.watchlist ? 'Remove From watchlist' : 'Add to watchlist'}
</button>
</div>
))}
</React.Fragment>
);
}
function Feed() {
const [feeds, setFeeds] = React.useState([]);
React.useEffect(() => {
//receiving data, for example fetching data by ajax or whatever
setFeeds(data);
}, []);
const handleAddToWatch = (id) => {
// implement updating feeds, for example making an ajax request and getting new data
setFeeds((feeds) =>
feeds.map((feed) => ({
...feed,
watchlist: feed.id == id ? true : feed.watchlist,
}))
);
};
const handleRemoveFromWatch = (id) => {
// implement updating feeds, for example making an ajax request and getting new data
setFeeds(feeds =>
feeds.map((feed) => ({
...feed,
watchlist: feed.id == id ? false : feed.watchlist,
}))
);
};
return (
<RenderFeeds
feeds={feeds}
onAddToWatch={handleAddToWatch}
onRemoveFromWatch={handleRemoveFromWatch}
/>
);
}
ReactDOM.render(<Feed/>, document.getElementById('root'))
.feed{
border: 2px solid #ccc;
padding: 15px;
margin: 15px;
}
.feed h1{ margin: 0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>
ReactJS: How to change Text value on button click
You're right, informed Text
doesn't have a prop value
, I found a trick on how to set the value of the Text
on a click of a button.
You can create a ref using React.createRef
to your Text then set the value via this ref.
class App extends React.Component {
constructor(props) {
super(props);
this.ref = React.createRef();
}
state = {
min: 10
};
changeQt = () => {
this.ref.current.value = 20;
};
render() {
return (
<div className="App">
<Text
initialValue={`${this.state.min}`}
field="quantity"
onChange={this.handleChange}
label=""
ref={this.ref}
/>
<button onClick={this.changeQt}>Click</button>
</div>
);
}
}
Demo here.
Change a button color when textinput is null, by using onPress
You use a controlled input field. You store the value in your state and you change it onChange with the input field. Next step is to set a style for your button depending on your current state.
<TextInput
style={[styles.input, value === '' ? styles.red : null]}
onChangeText={setValue}
value={value}
disabled
placeholder='Введите название дела...'
autoCorrect={false}
autoCapitalize='none'
/>
In this case you need to add a style called "red" which changes the button color.
red: {
backgroundColor: 'red'
}
Something like this.
Because your state is updated every time you change the input value, it gets updated onChange. If you want to set it on submit you need to add a isSubmitted boolean (default false ) to your state and set it to true in your pressHandler.
You need to destructure isSubmitted in this example:
style={[styles.input, value === '' && isSubmitted ? styles.red : null]}
How to display a random text from array on a button press in React Native?
Put it into state and display that state. Change state when button is clicked:
import { StatusBar } from 'expo-status-bar';
import React, { useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default function App() {
const [textValue, setTextValue] = useState('');
words = [...]
const changeTextValue = () => {
const len = words.length;
setTextValue(words[Math.floor(Math.random() * len)].text)
}
return (
<View style={styles.container}>
<Text>{textValue}</Text>
<Button onPress={changeTextValue} title='Press me'/>
<StatusBar style="auto" />
</View>
)
}
Related Topics
Display Current Date in Dd/Mm/Yyyy Format
Group By, and Sum, and Generate an Object for Each Array in JavaScript
Split a String Only the At the First N Occurrences of a Delimiter
Creating a Leaderboard in Html/Js
How to Read a Properties File in JavaScript from Project Directory
Close Window Automatically After Printing Dialog Closes
Get a Value from a Observable<Value> Object
How to Hide the Address Bar on Iphone
How Exactly Use and Update the Global Variables in React-Native
Passing Multiple Parameters from Angular to Rest Service
Draw a Connecting Line Between Two Elements
How to Hide the Parent Div If All Its Child Div Are Hidden
How to Add a Dynamic Action That Will Redirect to Another Page by Executing JavaScript Code
How to Change Size of Mat-Icon on Angular Material
How to Check a Radio Button in the Table Row Based on That Column Header
How to Enable Scrolling on Website That Disabled Scrolling
Center Content Vertically on Vuetify
How to Merge an Array of Objects With Same Keys in Es6 JavaScript