What is the best way to transfer the entered data from a TextField into a form after the user clicks a

I have a Text Input field and a Button (both are material-ui components) displayed on my main page. I would like the ability to click the button and transfer the existing text from the input field into a form, without creating a duplicate field. The current code I have only results in a new instance of the input field within the form. How can I achieve this without duplicating the input field?

FormTextField.js

const FormTextField = props => {
    return (
        <TextField
            fullWidth={true}
            multiline={true}
            rows="10"
            variant="outlined"
        >
        {props.data}
        </TextField>

    )
}

export default class FormTextField extends Component {
    render() {
    data={this.props.data} />
    return (

        {FormTextField}

        );
    }
};

Form.js

const Form= () => {
return (
    <FormLabel">Input Text...</FormLabel>
    <FormTextField />
);}
export default Form;

App.js

const AddButton= (props) => {
return (
    <Button variant="contained" onClick={props.onClick}>
    New Interaction
    </Button>
    )
}


export default class App extends Component {
constructor(props) {
    super(props);
    this.state = {show: false};
}
showForm = () => {
    this.setState({
        show: true,
    });
}
render() {
    return(
    <Fragment>
        <Header />
        <FormTextField />
        <AddButton onClick={this.showInteractionForm} />{this.state.show ? 
<Form /> : null}
    </Fragment>
    );
}

};

Answer №1

If you're looking to share data between two components, there are multiple ways to achieve this. One possible solution based on your code could be:

In your application, have the App component control the data like so:

Within your state, add:

this.state = {
 inputData: '';
}

You'll need to pass an update function to your FormTextField:

<FormTextField onTextUpdate={(text) => this.setState({ inputData: text })} />

Ensure that the form field is controlled by the App component by passing the data to be displayed as well:

<FormTextField data={this.state.inputData} onTextUpdate={(text) => this.setState({ inputData: text })} />

(Don't forget to make those modifications to the FormTextField component)

The final step is to also do the same with the Form component:

<Form data={this.state.inputData} onTextUpdate={(text) => this.setState({ inputData: text })} />

Inside the Form component, remember to pass the data and onTextUpdate props to the FormTextField.

You can refactor

(text) => this.setState({ inputData: text })
to be a method within the class.

EDIT

To see an implementation of what I've described, check out this CodeSandbox link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Centering Dynamic Text Vertically in Adobe Animate using Javascript

Adobe Animate CC Javascript Can someone share the correct way to vertically center text in a dynamic text box using Javascript within Adobe Animate? This is different from the typical CSS method of centering text vertically in HTML. The following code d ...

Error: Unable to change the value of "name" as it is set to read-only

Whenever I need to update the input value, I rely on the handleDepartmentChange function. const handleDepartmentChange = (companyIndex, departmentIndex, e) => { const newCompanies = [...companies]; newCompanies[companyIndex].children[departmen ...

The retrieval of data from the MySQL database using jQuery.ParseJson was unsuccessful

I have a div where I store a value retrieved from a database and parsed from JSON <div id='nsnt' class="huge"> </div> In my getdata.php file, I retrieve data from my MySQL database: getdata.php <?php $objConnect = mysql_co ...

Circular Dependencies in Singletons within CommonJS Modules

I am pondering the possibility and method of achieving the following: In a CommonJS environment, using modules for both node and browser (with Browserify). I have two (or more) modules that each return a singleton object that needs to be accessed in diff ...

Is there a way to append items to the main level of an array?

I am attempting to populate an array with objects in order to achieve the following structure: myobject1: Object: ItemInside: Object myobject2: Object ItemInside: Object myobject3: Object ItemInside: Object myobject4: Object ItemInside: Ob ...

Error: Surprising token found in ReactJS application on CodeSandbox

Encountering an unexpected token on line 5 error in my ReactJS project when testing it on CodeSandbox. Interestingly, the app runs smoothly without errors on my local machine. import React, { Component } from 'react'; import Header from ' ...

What is the best way to have a single item in a list displayed in two columns?

Can the angular repeat achieve this functionality? I am looking to loop the two elements together. Any assistance would be greatly appreciated! Controller: $scope.date=[ {ID:1,Date:'2016-11-12'}, {ID:2,Date:'2016-11-15'}, ...

Add the current date plus 48 hours to the content on a webpage (JavaScript maybe?)

Hello there, I am currently in the process of setting up a small online store for a farm using Squarespace. One thing I would like to implement is specifying that items will be available for pickup two days after they are purchased online, instead of imme ...

Is it possible to generate output from a string dust template without the need for prior compilation?

Can dustjs be used to dynamically render templates without compiling them first? > > var dust = require('dustjs-linkedin'); > > dust.stringRender("Hello {name}, how are you?", { name: "Joe" }, function(err, res) { > console. ...

Ways to categorize subordinate rows in Datatables

In my table, I have implemented child rows that can be expanded/collapsed. However, I am facing an issue where the parent rows contain duplicate data. According to the official Datatables documentation, the child rows are referred to as secondary rows. In ...

Encode data in JSON format using Javascript and then decode it using PHP

In my coding journey, I decided to create an object using Javascript to pass it as an argument to a PHP script. var pattern = new Object(); pattern['@id'] = ''; pattern['@num'] = ''; pattern.cprop = new Object(); // ...

Tips for selecting specific types from a list using generic types in TypeScript

Can anyone assist me in creating a function that retrieves all instances of a specified type from a list of candidates, each of which is derived from a shared parent class? For example, I attempted the following code: class A { p ...

What is the most efficient way to calculate the total of all numbers within a range using this particular JavaScript function?

Currently tackling a coding challenge on Free Code Camp The task involves receiving an array of two numbers and calculating the sum of those two numbers along with all numbers in between. The order of the numbers in the array is not fixed. While the sugg ...

Error occurred during the parsing of an AJAX response

Hello, I am currently exploring the world of JavaScript and jQuery. I recently encountered a situation where I initiated an AJAX call in my code and received an unexpected response. https://i.sstatic.net/AUHb7.png My current challenge revolves around imp ...

How to show ngFor value from Angular in a separate tag

I have a list of companies that I want to display in the following format: <div class="col-md-4"> <select ngModel="selectedCompany" style="width:400px;"> <option *ngFor="let x of mycompanylist&q ...

Building a JSON-powered navigation bar with Bootstrap 4

Looking to create a custom navigation bar using Bootstrap 4 and populate it with items from a JSON file. Despite researching various methods, there seems to be limited resources available on this topic. Any assistance or guidance would be greatly appreciat ...

Having trouble bypassing the alert in Google Chrome after automatically logging into Facebook using selenium-webdriver. I am using Javascript / JS language

const {Builder, By, Key} = require('selenium-webdriver'); const {Options} = require('selenium-webdriver/chrome'); const options = new Options().setAlertBehavior('dismiss'); let driver = new Builder().forBrowser('chrome&a ...

I'm puzzled as to why a div tag suddenly becomes invisible when I attempt to link it with a v-for directive in my code

I am facing an issue with the div tag assigned to the log class. My objective is to populate the text using data retrieved from the API response. However, when I attempt to include the v-for directive, the entire div mysteriously disappears from the brow ...

How can I use Jquery to animate an element to the right edge of the window?

Exploring the realm of jQuery animations, I am currently experimenting with animating a div to the right side of the window while changing its color using jQuery UI. This is just a fun project without any specific purpose in mind. Below is the code snippet ...

Modify the background color of a specific bar across multiple charts when hovering or clicking - utilizing chart.js

I have multiple chart.js canvas elements on a webpage. The goal is to be able to quickly identify and highlight the same bar value across all the charts. For example, when I hover over a bar called "Thu" on the first chart, I want to automatically search f ...