How to add text dynamic in defaultValue property with TextField from MUI - reactjs

I'd like to add Edited text after the message if the edit value is true.
How can I do that with TextField component from MUI?
import React, { useState } from "react";
import Box from "#mui/material/Box";
import TextField from "#mui/material/TextField";
export default function BasicTextFields() {
const [edit, setEdit] = useState(true);
const comment = "This is a comment from user.";
const message = `${comment} ${edit ? "Edited" : null}`;
return (
<Box component="form" noValidate autoComplete="off">
<TextField
id="outlined-basic"
label="Outlined"
variant="outlined"
defaultValue={message}
style={{ width: "300px" }}
/>
</Box>
);
}
Currently, I'm seeing This is a comment from user. Edited text when the edit is true and This is a comment from user. null text when the edit is false.
I just want to display Edited and don't need to show null.
Attempts
I tired
const message = `${comment} ${edit && "Edited"}`;
but this shows This is a comment from user. false text in the text input.

The null is being transformed into a string. Try instead:
const message = ${comment} ${edit ? "Edited" :""};

Related

Checkbox when clicked does not show text fields. collapse not working

I have this checkbox that when clicked doesn't show the text area I want to implement in collapse such that when the checkbox is clicked I want to see the content. the checkbox does not show the content when it's clicked
import React from 'react';
import { Grid, FormControlLabel, Checkbox} from '#mui/material';
import { Collapse } from 'react-collapse';
import { Formik } from 'formik';
import { useFormik } from 'formik';
import MyTextField from './MyTextField';
let defaultInitialIngestObject = {
pushEnabled: true
}
export default function App(props) {
const { initialValues } = props
const formik = useFormik({
initialValues: Boolean(initialValues) ? initialValues : defaultInitialIngestObject,
});
return (
<div>
<Grid item xs={12}>
<Grid item xs={4}>
<FormControlLabel
style={{ margin: 0, padding: 0, marginTop: '8px', verticalAlign: 'top' }}
label="Submit"
id="sub"
control={
< Checkbox size="large"
onClick={(evt) => formik.setFieldValue("sub", evt.target.checked)}
checked={formik.values['sub']}
/>
}
/>
</Grid>
<Collapse in={formik.values.sub}>
<Grid item xs={4}>
<MyTextField
disabled={formik.values.sub}
id="firs"
label="First"
formik={formik}
/>
</Grid>
</Collapse>
</Grid>
</div>
)
}
There are a few things needing adjustment.
First, you are trying to change an uncontrolled input to be controlled
causing this warning in the console
Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.
Let's address the issues.
The reason the warning it's happening is that you are mounting the input with a value of undefined, then later when you click on it you are setting a value of true [checked].
This will cause the error above, so lets predefine the value to be
false [unchecked]
checked={formik.values.sub || false}
Second, according to MUI Checkbox docs, the proper API is not onClick but onChange https://mui.com/material-ui/api/form-control-label/ , so, lets update that
onChange={
(evt) => formik.setFieldValue("sub", evt.target.checked)
}
Third, the property in doesn't seem to be in the API according to the library docs. https://www.npmjs.com/package/react-collapse
I changed it to isOpened and now it works.
<Collapse
// in={formik.values.sub}
isOpened={formik.values.sub}
>
I've created a sandbox here with a working version.
https://codesandbox.io/s/stackoverflow-example-checkbox-expand-8o2wzk?file=/src/App.js
PS. for your next issue, please provide a sandbox to make it easier for other to help out.

React- how to enable a button when TextField has value

So I'm trying to enable a button as soon as I enter a value in the TextField. The only way it is enabled is if i click outside the TextField after I put a value inside the Textfield. I know i'm missing something small but I still haven't found the correct way. I would appreciate your advice .
The code for the TextField and LoadingButton
the Window
I have included only the relevant part.
import { useState } from "react";
export default function Home() {
const [name, setName] = useState("");
const hanldeUserInput = (e) => {
setName(e.target.value);
};
return (
<Dialog>
<TextField onChange={hanldeUserInput} value={name} />
<LoadingButton disabled={name === ""}>Save</LoadingButton>
</Dialog>
);
}
You could keep track of the current value inside your textfield and store it inside the state.
const [txtFieldValue, setTxtFieldValue] = useState<string>('')
and write a function which is triggered on the change event in your textfield:
function handleTxtFieldChange(event) {
if (event.target.id === 'myTextFieldId') {
setTxtFieldValue(event.target.value)
}
}
And then you can adjust your textfield:
<TextField
id={'myTextFieldId'}
// ... all your other stuff
onChange={(event) => {
handleTxtFieldChange(event)
}}
/>
and you can then use the set txtFieldValue to render the button like:
{txtFieldValue != '' ? <Button /> : <></>}
or if you just want to disable it you can just use the
txtFieldValue != ''
as a boolean.

How to dynamically change a header text on Material UI dialogue with an if statement?

Modal.js
import { Dialog, DialogTitle, DialogContent, DialogActions } from "#material-ui/core";
const Modal = (props) => {
const { title } = props;
<Dialog>
<DialogTitle>
{title} // <- Where the dialog header text is passed into.
</DialogTitle>
<DialogContent/>
<DialogActions/>
</Dialog>
}
Main.js
I've create an if statement to change the header title between Add Information and Edit Information.
import Modal from "../Modal";
<Modal
title={() => {
if (materialValues.id === 0) { // <- materialValue.id = 0 if adding new information.
return "Add Information";
} else {
return "Edit Information";
}
}}
/>
I feel that this code should work, but it comes out empty without any error statement.
You are passing a function that is never called to return a value. Use a ternary operator to pass one or the other title value. The ternary expression will be immediately executed and the result passed in the title prop to the Modal component.
<Modal
title={materialValues.id === 0 ? "Add Material" : "Edit Material"}
/>

rectjs: material ui: TextField: show error if type and min is not valid

I am having a TextField, I want it to be number and also min=0.0001 i.e for number greater than zero
I am trying
<TextField
InputProps={{ inputProps: { min: 0.00001 } }}
type="number" id="outlined-basic"
/>
If i enter 0 in the input and leave, it does not show any error
min Input prop in html is validated only after the form is submitted (It will prevent the form from submitting if the values are invalid).
See Constraint Validation
If you want to use a realtime validation. You should consider using Formik
use error prop of rectjs: material ui: TextField :
my solution snippet for your doubt is :
import { TextField } from "#mui/material";
import React, { useState } from "react";
const App = () => {
const [num, setNum] = useState();
return (
<>
<TextField
InputProps={{ inputProps: { min: 0.00001 } }}
type={"number"}
value={num}
onChange={(e) => setNum(e.target.value)}
error={num && num < 0.00001}
/>
</>
);
};
export default App;
if you Enter number < 0.00001 that this TextField will be colored as Red

useRef reset textInput by Clicking button

i am using material-ui for my project and i am doing function to reset text of input to empty when clicking an outer button, it seem like not worked out
this is my code
var inputRef = useRef(null)
assign inputRef to the input field to access DOM
<TextField label="Student Name" ref={inputRef} />
an outer button to reset text field to empty when click it:
<Button variant="contained" color="primary" onClick={() => {inputRef.current.value = ""}}>
Reset
</Button>
and it unchanged, if it is possible, please modify the code in the codesandbox link here, thank you so much
You do incorrectly in step: assign inputRef to the input field to access DOM. It should be a ref of input element instead text field component (actual a div).
You should have state for value of Textfield Or using inputRef instead of ref to point to input element. Demo
import React, { useRef } from "react";
import { TextField, Button } from "#material-ui/core";
import "./styles.css";
export default function App() {
var inputRef = useRef(null);
return (
<div className="App">
<TextField label="Student Name" inputRef={inputRef} />
<Button
onClick={() => {
console.log(inputRef);
inputRef.current.value = "";
}}
variant="contained"
color="primary"
>
Reset
</Button>
</div>
);
}
useRef can be used on html DOM elements(<input/>). To pass ref to Material-UI input you should use inputRef property.
Please refer How can I use ref in TextField
var inputRef = useRef(null);
<TextField label="Student Name" inputRef={inputRef} />
demo

Resources