Skip to content
Advertisement

How do you achieve the below code in react-native when user presses a button

This is how we dynamically add elements in vanilla java script,how could this be achieved in react-native.

  let Message = '<div class="text-right " style="padding-bottom:5px;border-radius:25px;width:100%">' +
                '<div class="pl-5"  style="background:#f1f0e8 ;border-radius:25px;width:100%;">' +
                '<p class="pr-2 message" style="border-radius:25px;background-color:rgb(192, 192, 192);width:100%">' +
                $scope.message + 
                '<small>sent now</small>' +
                '</p>' +
                '</div>' +
                '</div>';

            $('.chat-box').append(Message)
            $scope.message = "";
            

Advertisement

Answer

The logic for this remains the same in both react and react-native. You need a state that contains the list of contents and must map that state to react components. On Button press, you have to append another content item. Unlike vanilla js you shouldn’t try storing components as string, rather use like the below example

import React, { useState } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';

export default function App() {
  // The state containing the content array which is set default to an empty array
  const [messages, setMessages] = useState([]);
  return (
    <View style={styles.container}>
      <View>
        {/* Map the state to a component list */}
        {messages.map((msg, index) => (
          <Text key={'msg-' + index}>Random Number Added - {msg.message}</Text>
        ))}
      </View>
      <View style={{ flexDirection: 'row',justifyContent: 'space-between' }}>
        <Button
          // Append a new message
          onPress={() => setMessages((m) => [...m, { message: Math.random() }])}
          title="Add"
        />
        <Button onPress={() => setMessages([])} title="Clear" />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'space-between',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});

Live Demo of the code: https://snack.expo.dev/@arnabxd/stackoverflow-72606009

You need to have a basic understanding of states in react.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement