obtain the content of a TextField element

In my React component that utilizes MaterialUI, I have created a simple form with a text field and a button:

export default function AddToDo() {

    const classes = useStyles();
    return (
        <div style={{
            display: "flex"
        }}>
            <TextField className={classes.textField} label="Add todo"></TextField>
            <Button variant="contained" >Submit</Button>
        </div>
    )

}

The goal is to call the method addNew(param1) when the submit button is clicked. The value of param1 should be the text entered by the user in the text field. Is there a way to achieve this functionality? For example:

<Button onclick=addNew(value inside the textfield) variant="contained" >Submit</Button>

Answer №1

To keep track of the field value, you must create a state variable and a callback function to update it:

const [inputText, setInputText] = React.useState("")

const handleInputChange = React.useCallback((event) => setInputText(event.currentTarget.value))

Add these attributes to the TextField component:

onChange={handleInputChange}
value={inputText}

This way, the value will be stored in the inputText variable

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

What is the best way to send a socket.io message to a particular user who is currently

When using socket.io with express and typescript, I am facing an issue where emitting to a particular logged-in user is not working. However, the rest of the functionality works fine such as when a new user joins. In my App.ts backend file, the code looks ...

What is the best way to calculate the variance between the most recent and previous data points in an array in the span of an hour using JavaScript

Here is an array of objects I am working with: 0: {time: '2021-12-02T23:53:54.062Z', value: 558316} 1: {time: '2021-12-03T00:53:53.959Z', value: 558452} 2: {time: '2021-12-03T01:53:53.934Z', value: 558588} 3: {time: '2021 ...

Manage the application of CSS media queries using JavaScript

Is there a method to control which CSS media query a browser follows using JavaScript? As an example, let's say we have the following CSS: p { color: red; } @media (max-width: 320px) { p { color: blue; } } @media (max-width: 480px) { p { col ...

sending an array from one CodeIgniter view to another view via Ajax

In the following code segments of my application, myArray is an array where each element contains a few objects that I need to use in a second view. When I use alert(myJSON);, I am able to see the array in the alert window. However, when the view loads, i ...

What is the best way to trigger a javascript modal to open automatically after a specific duration

Let's take an instance where my modal has the ID #modal1. It usually appears through a button-based action. ...

What could be causing my search function to not recognize special characters?

It seems like there might be an issue with character encoding. My JavaScript search function is unable to identify specific strings that contain certain special characters such as parentheses, asterisks, and numbers. The JavaScript code I am using is quit ...

Warning: Validation issue in console.js at line 213 - It is not valid for a <div> element to be nested inside a <p> element. Please correct this nesting validation

react-dom.development.js:86 Warning: validateDOMNesting(...): <p> cannot appear as a descendant of <p>. at p at http://localhost:5173/node_modules/.vite/deps/chunk-WQ5FBX7J.js?v=539aff10:2964:50 at Typography2 (http://localhost:5173/node_module ...

Unable to launch React Native project

Error: Module Not Found Cannot find module 'C:\Users\Admin\AppData\Local\npm-cache\_npx\7930a8670f922cdb\node_modules\@babel\parser\lib\index.js'. Please make sure that your package.jso ...

What are the best ways to integrate jQuery into a React application?

I am in the process of developing a responsive menu for my react app, but I'm facing some challenges as a newcomer to react. In order to achieve the desired functionality, I am trying to incorporate jQuery for menu toggling. However, when I attempt to ...

Is it possible to showcase multiple items in react JS based on logical operators?

How can I update the navigation bar to display different menu options based on the user's login status? When a user is logged in, the "Logout", "Add Product", and "Manage Inventory" options should be shown. If a user is not logged in, only the "Home" ...

JavaScript vanilla can be difficult to grasp, especially when it comes to

I'm experiencing a delay in displaying and hiding the mobile menu and table of contents section on my website when viewed on a mobile device. I'm using vanilla JavaScript to add and remove classes, but it's taking about one second for the me ...

I attempted to implement a CSS and Typescript animation for a sliding effect, but unfortunately, it isn't functioning

So I'm encountering an issue with this unique ts code: {/* Mobile Menu */} <div className="lg:hidden"> <button className="flex items-center w-8" onClick={toggleMenu}> {isMobileMenuOpen ? ( ...

Issue with Javascript form submission leading to incorrect outcomes

When setting the form action to a text retrieved from the database with an ID, I encountered a problem where it always displays the first ID even when clicking on text holding ID=2. Upon checking the page source, the correct IDs are shown for all texts. B ...

Use JQuery to reverse the most recent button click

Here is the code snippet I am working with: <button class="btn">New York</button> <button class="btn">Amsterdam</button> <button class="btn">New Jersey</button> <button class="btn&qu ...

Issue with Next.js production build (Clickable links malfunctioning)

After successfully building a website using next.js and expressjs, I encountered some issues in production that were not present during development. Here are a few points outlining the specific problems that only occur in production: Some links fail to ...

Perform an update followed by a removal操作

I've been facing a persistent issue that has been troubling me for quite some time now. The setup involves a database in MariaDB (using WAMP) and an API in ExpressJS. Within the database, there are two tables: "menu" and "item," with a foreign key rel ...

Issue encountered when trying to import an image URL as a background in CSS using Webpack

I have been trying to add a background image to my section in my SCSS file. The linear gradient is meant to darken the image, and I'm confident that the URL is correct. background-image: url(../../assets/img/hero-bg.jpg), linear-gradient(r ...

I'm having trouble viewing the items listed under a specific office. Every time I look at the dropdown menu, it appears to be empty with no

When a specific office is selected, the corresponding items should be displayed: If the office chosen is Building Management Office, the items Spalding Basketball and Mikasa Volleyball should be shown. If the office chosen is Information Technology Resour ...

VueJS form validation does not account for empty inputs in both fields

One of the challenges I'm facing is generating a form with Vue.js using the input fields below: { name: 'first_name', type: 'text', label: 'First Name', placeholder: 'First Name', ...

Skipping validation while navigating back on SmartWizardIf you need to bypass validation during backward

Looking for assistance with Jquery smartwizard? Check out the link. I want to disable validation when a user clicks on the "Previous" button in any step, except for the first step where the Previous button is disabled by default. Below is my JavaScript co ...