I am new to react. I am working on a project where I want to render checkboxes from an array that is coming from API response, where based on the phrase matching I have to group the options. i.e if item contains "BLR" it will group to all "BLR-" items
API response is :
[
"AU-COPS",
"BLR",
"BLR- End to End ACT testers",
"BLR-ACT-FUNCTIONAL",
"BLR-ACT-POLICY",
"BLR-ASM",
"BLR-ASM-FUNCTIONAL",
"BLR-ASM-POLICY",
"BLR-DAG",
"BLR-DEMO",
"BLR-MANAGED",
"BLR-QI",
"BLR-TOOLS",
"DE-COPS",
"demo-1",
"demo-2",
"ES- Audit (S&Q)",
"ES- Managed",
"ES-COPS",
"ES-Functional (managed/unmanaged)",
"FR- Audit (S&Q)",
"FR- Functional (managed/unmanaged)",
"FR-COPS",
"FR-Managed",
"IT- Functional (managed/unmanaged)",
"IT- Managed",
"IT-Audit (S&Q)",
"IT-COPS",
"JP-COPS",
"SEA-MANAGED",
"SJO-COPS",
]
For grouping, I have created one more array
var ch = ["BLR", "UK", "IT", "ES", "SEA"]
my code to render check box:
<div>
{listOfCheckboxes &&
checkBoxHeading.map((item, index) => {
return (
<>
<h8>{item}</h8>
<div key={index}>
{listOfCheckboxes.filter((childItem, childIndex) => {
if (childItem.includes(item))
return (
<div key={childIndex}>
<label htmlFor={childItem}>{childItem}</label>
<input
type="checkbox"
id={childItem}
name={childItem}
value={childItem}
></input>
</div>
);
})}
</div>
</>
);
})}
</div>;
Please help me guys!!
The output I am getting is listed all items without checkboxes.
Related
I am having issues correcting mysyntax in a React project. I get the error "Warning: Use the defaultValue or value props on instead of setting selected on ." However, I am unable currently to dynamically update the selected option for the drop down menu using just value/default value. The code updates 'correctly' when selected is used.
Relevant code below:
const Client = ({..., reactions}) => {
...
List Generator
function ReactionList() {
// retrieve and filter reactions
const availableReactions = reactions.filter(...)
return (
availableReactions.map((reaction, index) =>
<option key={index} value={reaction._id} selected={chosenReaction.name === reaction.name}>
{reaction.name}
</option>
)
)
}
// selecting reaction from drop down
function SelectReactionOption(entry){
setSelectedReactionId(entry);
setReactionPsiUpcast(0);
}
return (
...
<div className="DropDown">
<div>
<p>
Actions:
</p>
<select type="number" name={chosenAction.name} onChange={e => SelectActionOption(e.target.value) }>
<ActionList/>
</select>
</div>
</div>
i want to filter data based on the search query entered in input field from the values selected in dropdown menu.
What i am trying to do?
Consider the image below
From the select dropdown option user can select both messages and info or either of the options. Based on the option selected from dropdown menu and search query entered in the search input field it should filter data.
Suppose if user selected messages and entered search query "hello" it should retrieve messages containing text "hello" and similarly with info and messages option as well.
I am not sure how to do this. Could someone help me solve this?
Below is the code,
<div className='wrapper'>
<div>
{!state.expanded && <Svgsearch/>}
{state.expanded && props.active && <div onClick=
{this.collapse_input}><Svgsearch/></div>}
{state.expanded &&
<div className="search_input">
<input type="text" placeholder="search query" />
</div>}
<div className="search_dropdown">
<FieldDropdown on_dropdown_toggle=
{this.handle_dropdown_toggle} />
</div>
</div>
</div>);
export default class FieldDropdown extends react.component {
render = () => {
return (
<Dropdown className="category_dropdown" on_dropdown_open=
{this.handle_dropdown_open} on_dropdown_close=
{this.handle_dropdown_close}>
<div>
<button>{dropdown_text}</button>
</div>
{state.options.map((option, i) => {
return (
<DropdownItem key={i} on_select=
{this.handle_option_selection} value={i}>
<input type="checkbox" value={option.value}
checked="true" readOnly />
<span>
{option.text}</span>
</DropdownItem>)
})}
</Dropdown>);
};
Consider i have messages and info in an array of objects.
How can i write a method to filter data based on option selected from dropdown.
Thanks.
Html for query field
<input
id="searchId"
type="text"
value={this.state.queryValue}
onChange={this.handleTextChange}
/>
State
state = { data: [], filteredData:[],queryValue: '' ,value:'' };
Event Handling Method
handleTextChange = event => {
//read the value of the textbox with event.target.value
const filteredData = this.state.data.filter(d =>
// object where condition based on value(options value) & queryValue
);
this.setState({ queryValue: event.target.value, filteredData});
};
and bind UI to the filteredData.
I am receiving a very unusual error with my Object. I am trying to get the value of the key name from an object which looks like this
{id: 3,
image_url: "anticon anticon-gift",
is_deleted: false,
name: "Inform Partners",
org_id: null",}
The thing is I have an object coming from a state in a variable let us say this.state.description_data it looks like this
As you can see I am getting a category_id in it. I want to match that category_id from another state object which is
Now, I want to match the category_id iIgot from description_data with the id in category_data and get the value of name from it and show it in the render. I get the value but after a few refreshing or by going out of the page and coming back in it shows me error as follows
I have tried this code to get the value
var defaultCategoryId= this.state.description_data.map(c=>{
return c.category_id
});
console.log("description_data")
console.log(this.state.description_data)
console.log(defaultCategoryId[0])
console.log(this.state.category_data)
let catId= defaultCategoryId[0] -1;
let defaultCategoryValue = this.state.category_data[catId];
// let catValue=defaultCategoryValue.map(c=>{
// return c.name
// });
console.log(defaultCategoryValue);
The object i mentioned above is being generated in the variable let defaultCategoryValue
I am using the defaultCategoryValue.name in render method which looks like this:
return (
<Spin spinning={this.state.loading} tip="Loading..." indicator={antIcon} delay={500} size="large">
{this.state.cover_show===false?<div>
{this.state.description_data.map(d=>
<div key={d.id}>
<Row key={d.id} style={rowStyle} gutter={gutter} justify="start" style={{marginBottom: "10px"}}>
<Col md={16} sm={12} xs={24} >
<div className="form-element">
<label className="label-class" title="">Production Name <Tooltip title="This is a name used that you can use to uniquely identify your production, making it easier for you and your contributors to find it. We recommend the name be a few words that describe the nature of the project."><Icon className="tooltip-icon" type="question-circle-o" /></Tooltip> </label>
<Input className="txt-font" name="display_app_name" id={"display_app_name-" + d.id} maxLength={70} defaultValue={d.display_app_name} onChange={this.ontxtChange} />
<span className="error-text">{this.validator.message('display_app_name', d.display_app_name, 'required|max:70', false, { default: 'This field is required.',max:'You have exceeded the maximum character limit.' })}</span>
<p style={{float:"right"}}>{d.display_app_name.length}/70</p>
</div>
<div className="form-element">
<label className="label-class" title="">Category <Tooltip title="This is where you can specify which of the options most closely aligns with the purpose of the video. If you are using a pre-built storyboard, this will have already been selected for you."><Icon className="tooltip-icon" type="question-circle-o" /></Tooltip> </label>
<Select defaultValue={defaultCategoryValue.name} onChange={this.onCategoryChange} id={"category_id-" + d.id}>
{categoryOptions}
</Select>
<span className="error-text">{this.validator.message('category_id', d.category_id, 'required', false, { default: 'This field is required.'})}</span>
</div>
Probably the way i am getting the value is wrong. I am assuming this because if i dont type defaultCategoryValue.name and write d.category_id i dont get any error. The defaultCategoryValue always revieves the data no matter how many times i refresh. But it shows error sometimes if you use it in <Select defaultValue={defaultCategoryValue.name> as you can see above in the code.
Please help me with this guys. Thank you.
Given the shape for this.state.description_data to be
[
{
//...
category_id
//...
}
]
and this.state.category_data to be
[
{
//...
id
//...
}
]
It seems about right to convert this.state.category_data from an array to an object having its keys to be the category_id. This will make it easier to lookup the category data for a category_id when mapping this.state.description_data
const CATEGORY_DATA = this.state.category_data.reduce(
(categories, category) => (
{...categories, [category.id]: category}
),
{}
)
Now, this.state.description_data can be mapped to its category data in the following way.
this.state.description_data.map(
(description) => (
<div key={description.id}>
//...
<Select
defaultValue={CATEGORY_DATA[description.category_id]}
id={"category_id-" + description.id}
onChange={this.onCategoryChange}
>
{categoryOptions}
</Select>
//...
</div>
)
)
I'm using react-bootstrap-typeahead and I would like all available options to be shown if the input value is an exact match to one of them. I mean if the user writes a value that matches with one of the options I want to display all the options (and make the matched one active) instead of just the one that matches.
I tried using the renderMenu prop of Typeahead but I'm unable to achieve the expected behavior. This is my code:
render() {
let options = this.state.options;
let optionsValues = this.state.options.map(v => v.value);
let value = this.state.inputValue;
if ( optionsValues.includes(value) ) {
const TypeaheadMenuItem = menuItemContainer(MenuItem);
return (
<div className="col-4">
<label className="form-group has-float-label" name={this.props.name}>
<Typeahead
labelKey="value"
onInputChange={this.updateInputValue}
selected={[this.state.inputValue]}
options={options}
placeholder={this.props.name}
selectHintOnEnter={true}
disabled={this.props.disabled}
renderMenu={(results, menuProps) => {
return (
<Menu {...menuProps}>
{options.map((opt, ind) =>
<TypeaheadMenuItem option={opt} key={ind} position={ind} active={opt.value==value}>
{opt.value}
</TypeaheadMenuItem>
)}
</Menu>
);
}}
/>
<span><b>{this.props.name}</b></span>
<div className="invalid-feedback"></div>
</label>
</div>
)
}
}
I can see the options but for some reason all the options have the prop active as true.
Actual Behavior
Here is a screenshot of how my component behaves right now:
https://gyazo.com/9cbb9842654d681f7ff3e1a2e663e09e
Working on the setting security questions part of the authentication. The server responds with a list of the 20 or so questions in the form of an array. I can get the form and select box to render, but only one option at a time by specifying the index.
If I try to send the entire array I get an undefined error. Tried to do a for loop in the ` to iterate through each index, which generated an error.
I'm trying to figure out how to pass the entire array so it makes an option for each entry in the array.
This is what I have so far:
// ./set_security_questions.js
// This renders errors regarding the form inputs
renderField(field) {
const {
label,
placeholder,
type,
name,
questions,
meta: {
touched,
error
}
} = field;
return (
<div className='form-group'>
<label>{label}</label>
<select className='form-control' name={name}>
<option value={questions}>{questions}
</option>}
</select>
<input
className='form-control'
type={type}
placeholder={placeholder}
{...field.input}
/>
<div className='text-danger'>
{touched ? error : ""}
</div>
</div>
);
}
// The main body to be rendered
render() {
if (this.props.permitRender) {
const { handleSubmit } = this.props;
return (
<div>
<h3>Set Security Questions</h3>
<p>Please select two security questions that will be easy for you to remember.</p>
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
{this.renderAlert()}
<Field
questions={this.props.questions.data.security_question}
label='Question 1'
placeholder='Answer 1'
name='a1'
type='text'
component={this.renderField}
/>
<Field
label='Question 2'
placeholder='Answer 2'
name='a2'
type='text'
component={this.renderField}
/>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
);
} else if (!this.props.permitRender) {
return (
<div> { this.renderAlert() } </div>
);
}
}
In addition, my JSON that comes back from the server looks pretty strange, so I will need to iron that out, but still wondering how to pass an array into the Form. this.props.questions.data:
data:
id: 123
key: "key_request"
security_q1: null
security_q2: null
security_question: Array(29)
0: {security_question: "In what city or town did you meet your spouse / partner?"}
1: {security_question: "In what city or town did your mother and father meet?"}
2: {security_question: "In what town or city was your first full time job?"}
3: {security_question: "What is the first name of your spouse's father?"}
......
Here is an example I'm currently using to populate a set of checkboxes. There isn't any special logic going on in the checkbox component, I just am using custom html for styling purposes.
Here is my data, a simple array:
const env = {
FONT_FORMATS: ['OTF', 'TTF', 'WOFF', 'WOFF2']
}
Here is the code in the render() function for my component. I'm storing each item in the Redux form under the object key -> fileTypes.
<ul className='tags'>
{envConfig.FONT_FORMATS.map((tag: string) => (
<Field
key={tag}
value={tag}
name={`fileTypes.[${tag}]`}
id={tag.toLowerCase().replace(' ', '_')}
type='checkbox'
component={checkBox}
label={tag}
/>
))}
</ul>
I hope this helps you out!