Open In App

How to get text inside Text component onPress in ReactJS ?

In this article, we will learn “How to get the text inside Text component onPress in ReactJS?”.

Problem Statement: Sometimes in an application, it is required to get the text inside certain components, in order to reuse the components again & again just by changing the text value.



Approach: We will set the property inside the component’s tag to which we want to send text, then inside that component, we will use props to get that text value and use it inside the return statement to print that text to the browser.

Implementation: Below is the step-by-step implementation of the above approach.



Creating React Project:

Step 1: To create a react app you need to install react modules through npx command. “npx” is used instead of “npm” because you will be needing this command in your app’s lifecycle only once.

npx create-react-app project_name

Step 2: After creating your react project move into the folder to perform different operations.

cd project_name

Step 3: Open the folder inside the code editor, and delete all the files inside the “src” folder except the index.js file, and all the files inside the public folder. Now, open the terminal and type the following command to create “index.html” files in the public folder:

cd public
touch index.html

And  “App.js” and “Text.js” in the src folder:

cd src
touch App.js Text.js

Project Structure: We have a simple project structure, we have a package.json & package-lock.json file which contains the details about the module installed inside this project. Then we have node_modules which contains the actual module and an “index.js” file inside “src”, our main server file. We also have “App.js” and “Text.js” file which is React.js component files.

 

Example: 




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="utf-8" />
    <meta name="viewport" 
          content="width=device-width, initial-scale=1" />
    <title>React App</title>
</head>
  
<body>
    <div id="root"></div>
</body>
  
</html>




import Text from "./Text";
  
function App() {
    return (
        <div>
            <h1>Geeks For Geeks</h1>
            < Text text="How to get text inside 
            Text component onPress in ReactJS" />
        </div>
    );
}
  
export default App;




function Text(props) {
    return (
        <div>
            <h3>{props.text}</h3>
        </div>
    );
}
  
export default Text;

Steps to Run: Open the terminal, and type the following command to run the application 

npm start

Output:

 

The output shows that the data we set inside the text property of the Text tag will send to the Text Component and then we get that data to the Text component, pass that data into an h3 heading and send it back to the browser, that’s why it is visible to us.


Article Tags :