Material UI checkbox toggle value based off input from object - javascript

I have an unchecked checkbox. I am trying to change the value of it based off of data from an object. The object is from an SQL select boolean column 'T' or 'F'. If the value is 'T' then the box would be checked vise versa. I tried using a useState() that viewed the value but that didn't work.
const [checkBoxState, setCheckBoxState] = React.useState(false);
//check to see if values are 't' or 'f' to change them to vaiable formats
function handleCheckState(databaseCondition) {
if (databaseCondition == "T") {
setCheckBoxState = true;
}
console.log(checkBoxState);
return checkBoxState;
}
This is the useState() I tried using.
<Checkbox checked={handleCheckState(data["validcycle"])} />
Here is the checkbox I want to toggle on/off based off that sql column.

Friend, you forgot to enclose hook in brackets, example : setState(value)
const [checkBoxState, setCheckBoxState] = React.useState(false)
function handleCheckState(databaseCondition) {
if (databaseCondition == 'T') setCheckBoxState(true)
else setCheckBoxState(false)
return checkBoxState
}

you must change the state using:
setCheckBoxState(true);
instead of:
setCheckBoxState = true;
the better approach is simply like this:
<Checkbox checked={databaseCondition === "T"} />

Related

Clearing a Material UI search filter TextField and returning to default

I am new to ReactJS and pairing it with Material UI is really causing me some roadblocks. I have created a reusable search filter component for my data tables and it worked exactly the way I wanted, but now I want to add a button to clear the field and show the unfiltered results, as well as return the InputSearch component back to its default state so it will display the label inside the field again, not up in the field’s border as these Material UI TextFields do then they are focused or have a current value. This is where I am hitting my roadblock. I have tried multiple solutions I found online, like using the inputRef/useCallback method to change the values, but it didn’t seem to work…or maybe I misunderstood and did it wrong. I was also recommended to put my search values to state. As happens with state my searches are now always one render behind (I.E. , results matching ‘US’ for ‘USA’ , ‘USA’ for ‘USAF’, etc…). Then when I run the handleFilterReset function to set the filter values back to an empty string, nothing happens. I just want my search filter to work instantly (like it did before I moved the value to state [commented out]) and be able to be cleared, resetting the table back to its default display.
Can someone please help me figure this out? Suggestions are appreciated, but code snippets are much more helpful since I am really new to React and especially Material UI.
dataTable.js
const [inputValue, setInputValue] = useState('')
const [searchFn, setSearchFn,] = useState({ fn: items => { return items; } });
// Searching Data
const handleSearch = e => {
setInputValue(e.target.value) // value displayed in input field
let query = (e.target.value).toString().toLowerCase();
setSearchFn({
fn: items => {
if (query === "")
return items;
else
return items.filter(x =>
(x.tankName !== null && x.tankName.toLowerCase().includes(query)) ||
(x.dimensions !== null && x.dimensions.toLowerCase().includes(query))
)
}
})
}
// Clearing Filters
const handleFilterReset = () => {
setInputValue('');
setSearchFn({fn: items => {return items;}})
};
// Search and filter Inputs
<div>
<InputSearch
value={inputValue}
onChange={handleSearch}
/>
<Button
text="Reset"
onClick={handleFilterReset}
/>
</div>
InputSearch.js
export default function InputSearch(props) {
const { inputRef, name, value, error=null, onChange, ...other } = props;
return (
<TextField
label="Search..."
name={name}
value={value}
onChange={onChange}
{...other}
{...(error && {error:true, helperText:error})}
>
</TextField>
)
}
You need to pass the value to InputSearch
Heres an example:
https://codesandbox.io/s/morning-brook-durbvd?file=/demo.tsx
React has a pretty good introduction on its site.
https://reactjs.org/docs/components-and-props.html
The code has been updated with a solution to this issue. I created a display value for the input that I passed to state, which was set to a blank string when the reset is pressed as well as passing an unfiltered data set.

Is there a way to check every input field for a missing value?

I want to be able to display a ul tag with all the fields missing a value.
I want to check if the question, category, and gender are empty. As well as the consent is false.
Then I want to display a message like this
<h2>missing fields</h2>
<ul>
<li>question</li/>
<li>category</li/>
<li>gender</li/>
<li>consent</li/>
</ul>
Right now I have these functions:
let handleInputChange = event => {
const target = event.target;
const value = target.value;
const name = target.name;
setValues({
...values,
[name]: value,
});
};
let handleCheckboxChange = event => {
const target = event.target;
const value = target.checked;
const name = target.name;
setValues({
...values,
[name]: value,
});
};
If for example the consent is set to true, then it should not appear when submitting the form
I think the following should work for you :-
<h2>missing fields</h2>
<ul>
{Object.keys(values).filter(key=>key==='')).map(val=><li>val</li>)}
{!values.consent && <li>consent</li>}
</ul>
Here we are getting all the keys of your values state in an array and filtering out only the ones which are equal to '' and then map over them to display as li elements.
For consent we can explicitly handle it using && i.e. only render this li element when consent is false.
Or you can also have one dedicated function like renderMissingFields where if you expect your fields to increase overtime you can write some custom logic like above but for this particular use case, above should suffice.
Also you can follow the rendering approach for other fields (for which I used Object.keys) same as consent.
In case you want all of them to fit the constraints as defined by you and only then render , you can do something like this :-
{!(question!=='' || gender!=='' || category!=='' || consent) &&
(<h2>missing fields</h2>
<ul>
<li>question</li/>
<li>category</li/>
<li>gender</li/>
<li>consent</li/>
</ul>
)
}

Edit TextField with value already filled doesn't work

I'm beginner with React JS and I'm doing a test project to train my skills.
I have a list of farms being rendered on the screen. The user can click on the button to register a new farm or can click on the property to be able to edit the existing property.
In a single Dialog Modal I do both. The problem is when I try to edit the Input field, it is not working. It doesn't matter what I type and nothing happens.
That's my input field, I'm using TextField from React Material:
<TextField
id="farmer-name"
label="Farm Name"
value={propertyData.farmerName}
onChange={(event) =>
changeField("farmerName", propertyData.id, event.target.value)
}
className={classes.input}
InputProps={{
className: classes.inputContent
}}
InputLabelProps={{
className: classes.inputLabel
}}
/>
And here's my function that will be able update my data:
const changeField = (field, id, value) => {
const newPropertyData = { ...propertyData };
if (newPropertyData.id === id) {
newPropertyData.field = value;
}
};
Here's my code, I put in CodeSandBox: https://codesandbox.io/s/spring-breeze-xnv3r?file=/src/index.js
Screen of my application
Can someone help me to edit that´s values? Thanks
You should save state on change in text field
const changeField = (field, id, value) => {
const newPropertyData = { ...propertyData };
if (newPropertyData.id === id) {
// change field value for specific id
newPropertyData[field] = value;
}
// set updated field value into state to show on form
setPropertyData(newPropertyData);
};
You are not actually changing the propertyData stored in the useState hook.
Currently, there will be a new property added called field in the newPropertyData object. However, this variable is never used or stored and you probably don't want the value to be stored in the field property.
The shortest answer is to pass a function to the setPropertyData which will receive the previous value of propertyData.
The previous propertyData can be extended with a dynamic property by using the following syntax: [field]: value.
const changeField = (field, id, value) => {
if (propertyData.id === id) {
setPropertyData(data => ({ ...data, [field]: value }));
}
};

How to add dynamic input values to the local state for retrieval

I have a React Native form that allows me to add an Input UI in the form, by clicking a button with this function. This allow me to generate it on the fly. The code for that is this.
addClick() {
this.setState(prevState => ({ values: [...prevState.values, ""] }));
console.log(this.values[0].name);
}
That part works well, but I'm having a problem extracting the data from the dynamic inputs, and add it to an array. So far I have tried this
setVal = value => {
const values = this.state.values[0];
if (values[0].name === "" || values[0].description === "") return;
[...this.state.values, value];
this.setState(values);
console.log(values);
};
How do I organize my states properly so that I can add as many inputs I need, and when I'm finished, I can update the state, and access the new data in my list component?
How do I update my state to the new Array? at the moment, this.state only shows the initial state set at the top.
I'm missing a few things
Please take a look at the full code sandbox HERE so you can see:
See...your created isssue is not so obvious we need to see where you call setVal() function but....
i think you will be more comfortable if you render your <input/> s directly from your state array, not from const x = [] variant. because it seems like you want a dynamic view and in such a cases you will need to bind your loop quantity from state. so:
this.state = {
x: [0,1,2,3,4]
}
and inside your render :
{this.state.x.map(x => {
return (
<TextInput
placeholder={`name${x}`}
value={values[x.toString()]}
handleBlur={() => handleBlur(x.toString())}
onChangeText={handleChange(x.toString())}
style={styles.input}
/>
);
})}

How to change row color in datatables?

I am using datatables and currently stuck in changing a row to another color if value = INACTIVE, already tried many things but it has really weird error, my codes are :
"createdRow": function (row, data, dataIndex) {
if (data[9] = "INACTIVE") {
$(row).addClass("yellow");
} else {
$(row).addClass("white");
}
}
This code change all color row, but i want only change value INACTIVE
Thanks for the help!
You have a typo in your code.
In your if statement use == instead of =.
"createdRow": function (row, data, dataIndex) {
if (data[9] == "INACTIVE") {
$(row).addClass("yellow");
} else {
$(row).addClass("white");
}
}
In the condition, you are assigning the value "INACTIVE" to the data[9] instead of comparing the value. Subsequently, the condition only checks whether data[9] has some value, which is true, and class .yellow is always added.
So the condition should be like this if (data[9] == "INACTIVE") or rather if (data[9] === "INACTIVE") to perform check without type conversion.
In your if statement you are using a single '=' which is used for assignment. You should use double '=' to compare if the value is the same and triple '=' to compare if the value and the data types are the same.
You are also only checking index 9 of data. In your function you seem to also be passing in the index, you should instead change your code to something like this.
if ( data[ dataIndex ] === "INACTIVE" )

Categories