Adding a className if a condition is true - css

i have a form with multiple fields and a submit button. once i click the submit button it will come to this filterProperties function. i have a if condition inside that filterProperties function. so in that if condition i am checking whether the check-out date is null. if the if-condition is true i want to add has-error class to the datepicker. if anyone knows how to do this please help.
filterProperties = () => {
let checkin = this.state.checkin;
let checkout = this.state.checkout;
let guestCount = this.state.guest_count;
let cityID = this.state.selectedcityID;
let budget = parseFloat(this.state.textthree).toFixed(2);
if (checkin !== "" && checkout === '') {
alert('plz enter the check out date');
}
const cityProperties = {
checkin: checkin,
checkout: checkout,
guestCount: guestCount,
cityID: cityID,
budget: budget
}
console.log(cityProperties);
this.props.getCityProperties(cityProperties);
}
<FormItem style={{ marginBottom: '0' }} label="Check Out">
<span>
{getFieldDecorator('check_out', {
rules: [
{
required: true,
message: 'Please select a Check Out Date',
}, {
validator: this.checkCheckoutDates,
}
],
})(<DatePicker
className={className}
disabled={(this.state.checkin === '')}
disabledDate={this.disabledDateCheckout}
onChange={(e) => this.dateSelected(e, 'checkout')}
defaultValue={moment(new Date((new Date()).valueOf() + 1000 * 60 * 60 * 24))}
format={dateFormat}
/>)}
</span>
</FormItem>

Try this-
<DatePicker
className={(this.state.checkin !== "" && this.state.checkout === "")? "class-name": ""}
disabled={(this.state.checkin === '')}
disabledDate={this.disabledDateCheckout}
onChange={(e) => this.dateSelected(e, 'checkout')}
defaultValue={moment(new Date((new Date()).valueOf() + 1000 * 60 * 60 * 24))}
format={dateFormat}
/>

You can use something like this
<Element className={`${this.state.flag ? className : ''}`} />

Related

How can I have a multivalue global filter in react-table v7?

I have a search bar as a globalfilter but I want to know if in react-table v7 it is possible to have multivalue in it for example.
I want to search words and it search in all my columns not the exact string but each word in each column.
This is my search input
const TableSearchFilter = ({ preGlobalFilteredRows, globalFilter, setGlobalFilter }) => {
return (<Input
value={globalFilter || ""}
onKeyDown={(e) => {
if (e.keyCode ==13) {
e.preventDefault()
}
}}
onChange={(e) => {
setGlobalFilter(e.target.value)
}}
startAdornment={<i className="fas fa-search" style={{ marginRight:'10px' }}></i>}
/>)
}

How to manually re-render component using react-hook-form when validation errors are updated

facing challenges making validation classes to reflect automatically on custom datepicker Flatpickr using React-Hook-Forms,
const { register, handleSubmit, errors, control } = useForm({
mode: 'onChange'
})
<FormGroup>
<Controller
name="dateControl"
control={control}
defaultValue={null}
rules={{ required: true }}
render={({ value, onChange }) => (
<Flatpickr
value={value}
onChange={onChange}
id="hf-picker"
options={{
altInput: true,
altFormat: 'F j, Y',
dateFormat: 'Y-m-d',
altInputClass: classnames(
'form-control flatpickr-input',
{
'is-invalid': errors.dateControl && true
}
)
}}
/>
)}
/>
</FormGroup>
After troubleshooting, I realize everything works except that component fails to re-render whenever the validation errors are updated by react-hooks-form, is there anyway I can force a manual re-render instead, thanks
I think this has nothing to do with RHF, but somehow the options prop of the <Flatpickr /> component isn't updated when the config changes.
I'm assuming your using the react-flatpickr package - what you could do is simply pass the key prop to this component and setting it to the errors object of that control. This will force a re-render every time the errors of that form control change.
const isNotEmpty = (array) => array?.length > 0 || "Required";
<Controller
name="dateControl"
control={control}
defaultValue={null}
rules={{ validate: isNotEmpty }}
render={({ value, onChange }) => (
<>
<Flatpickr
key={errors.dateControl}
value={value}
onChange={onChange}
id="hf-picker"
options={{
altInput: true,
altFormat: "F j, Y",
dateFormat: "Y-m-d",
altInputClass: classnames("form-control flatpickr-input", {
"is-invalid": !!errors.dateControl
})
}}
/>
{errors.dateControl && <p>{errors.dateControl.message}</p>}
</>
)}
/>

How can I change className for specific element when mapping?

I am trying to change the index 5 and 6 to opacity 0.2 but I do not know how to change specific className when mapping in react
Here is my following code:
const tabs = [
"Mission",
"Agreement",
"Calendar",
"Managers",
"Members",
"Invitees",
"Applicants",
"Sub-Team",
];
const [activeTab, setActiveTab] = useState(0);
<div className="team-management-tab-items">
{tabs.map((tab, index) => (
<div
className={
activeTab === index
? "team-management-tab-item selected"
: "team-management-tab-item"
}
key={tab}
role="button"
tabIndex={tab}
onKeyPress={() => {
return;
}}
onClick={() => {
if (editable === true) {
setActiveTab(index);
} else if (index !== 5 && index !== 6) {
setActiveTab(index);
}
}}
>
<span className="tab-item-text">{tab}</span>
<span className="tab-item-indicator" />
</div>
))}
</div>
</div>
<div className="team-management-tab-panes">
{tabs[activeTab] === "Mission" && (
<Mission
editable={editable}
teamId={teamId}
teamData={teamData}
fetchTeamData={fetchTeamData}
/>
)}
{tabs[activeTab] === "Agreement" && (
<Agreement
teamData={teamData}
agreement={agreement}
editable={editable}
teamId={teamId}
fetchTeamData={fetchTeamData}
/>
)}
...
);
Here is how my project look like:
So basically I want to change opacity Invitees and Applicants to 0.2. How can I do that?
There are a few ways to do this, the easiest would likely be adding an id tag to the div like:
{tabs.map((tab, index) => (
<div
id = {tab}
className={
activeTab === index
? "team-management-tab-item selected"
: "team-management-tab-item"
}
and then in your css just add
#Invitees, #Applicants{
opacity: 0.2;
}

React - Ant Design 4 Form InitialValues / form.setFieldsValue

I tried it also with the "Form initialValues={system}" but the Input fields are still empty. My object has only string values.
Why cant the setFieldsValue or the initialValues read my object?
const ResetFields = () => {
form.resetFields();
form.setFieldsValue({
'name': 'Test', //working
'street': system.street, //not working (type is string)
houseNumber: system.houseNumber, //not working (type is string)
postCode: system.postCode,
city: system.city
});
}
return (
<div>
<Form
{...layout}
size={"large"}
form={form}
validateTrigger="submit"
onReset={ResetFields}
onFinish={Submit}
validateMessages={validateMessages}
>
<Form.Item
name='name'
label="Name"
rules={[{ required: true }]}
>
<Input autoComplete="off" />
</Form.Item>
//More Form.Item and Buttons Submit and Reset...
</Form>
</div>
);
I had a similar issue, try this. maybe that will help.
'street': system?.street

Material UI Selected Option Not Showing in Select Box

I have the following:
--- before render ---
const fontArray = [
["Standard", "Standard"], ["Abril FatFace", "'Abril Fatface', cursive"],
["Alfa Slab One", "'Alfa Slab One', cursive"],
["Chonburi", "'Chonburi', cursive"], ["Comfortaa", "'Comfortaa', cursive"],
["Lobster", "'Lobster', cursive"], ["Pacfico", "'Pacifico', cursive"]
]
--- in render ---
<FormControl style={{margin: '10px'}}>
<InputLabel htmlFor="select-font">Font</InputLabel>
<Select
value={this.state.font[0]}
onChange={(evt)=>this.handleFontChange(evt)}
inputProps={{
name: 'font',
id: 'select-font',
}}
>
{fontArray.map((font, index)=>{
return(
<MenuItem key={font} value={font}>
<div style={{fontFamily: `${font[1]}`}}>
{font[0]}
</div>
</MenuItem>
)
})}
</Select>
</FormControl>
And as you can guess the current font is held in state.
--- Here is how I handle select change ---
handleFontChange = (event) => {
this.setState({ font: event.target.value })
};
So what I want is to be able to have a font select, where the font is shown. It almost works. For example, when I click the select I get:
However, the select itself is empty (even when I've confirmed that state is populated:
What am I doing wrong? Maybe material-ui can't handle stylized default text?
EDIT: The two answers below seem close, but not quite right for what I'm trying to do.
If you replace
<MenuItem key={font} value={font}>
with
<MenuItem key={font} value={font[0]}>
It does replace the font with the correct selected value. Great!
...but it also then replaces this.state.font with this.state.font[0]. I'm currently attempting to get this to work by changing the handle function like this:
handleFontChange = (event, fontArray, stateData) => {
let newFont = fontArray.filter(i=>{
if(i[0]==event.target.value){
return i
}
})
this.setState({ font: newFont })
};
Which seems to set this.state.font correctly, but it again doesn't
seem to want to make the select box show the selected font.
Hmmm....
SOLVED
Here is a modification of a solution below:
Using
renderValue = (value) => {
return(
<div style={{fontFamily: `${value[1]}`}}>
{value[0]}
</div>
)
}
and
<...>
<Select
value={this.state.font}
renderValue={() => this.renderValue(this.state.font)}
<...>
Gives...
You can use renderValue to solve this.
renderValue = (value) => {
return value && value[0];
}
in render method
<FormControl style={{margin: 10}}>
<InputLabel htmlFor="select-font">Font</InputLabel>
<Select
value={this.state.font}
renderValue={() => this.renderValue(this.state.font)}
onChange={evt => this.handleFontChange(evt)}
inputProps={{
name: "font",
id: "select-font"
}}
>
{fontArray.map((font, index) => {
return (
<MenuItem key={index} value={font}>
<div style={{fontFamily: `${font[1]}`}}>
{font[0]}
</div>
</MenuItem>
);
})}
</Select>
</FormControl>
<...>
<Select
value={this.state.font?this.state.font :defaultvlue}
renderValue={() => this.renderValue(this.state.font)}
<...>
you can use ternary operator ,if you have data show data else default value

Resources