Why is selected not an option for React? - reactjs

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>

Related

get the value from select option inside <li> react

I have multiple select options based on the database all are displayed inside a li tag in the following format.
<ul>
here select options are rendered in a for loop;
<li>
<select>
<option value='xxx'></option>
<option value='yyy'></option>
</select>
<button
onClick={set(selectedvalue)}
>
set
</button>
</li>
</ul>
each li will have an seperate set button how do i pass the selected value to the function.i cant use the useState since it may have many li.
This can be achieved using useRef then getting the value from the reference to the select select. You will pass the ref into the set function and that should allow you to grab the value through current:
import React, { useRef } from "react";
const SelectExample = () => {
const select1 = useRef(null);
const set = (setRef) => {
console.log(setRef.current.value);
};
return (
<ul>
here select options are rendered in a for loop;
<li>
<select ref={select1}>
<option value="xxx"></option>
<option value="yyy"></option>
</select>
<button onClick={set(select1)}>set</button>
</li>
</ul>
);
};
export default SelectExample;
useRef() is certainly one way to get this done.
The first thing you want to do is create a ref to tie to your select:
const selectRef = useRef();
Then link up the select element to the ref like so:
<ul>
<li>
<select ref={selectRef}>
{ar.map((i, index) => (
<option key={index} value={i}>
option {i}
</option>
))}
</select>
<button onClick={() => set(selectRef.current.value)}>set</button>
</li>
</ul>
As you can see, the button will grab the current value of the select and send it to your set function.
<button onClick={() => set(selectRef.current.value)}>set</button>
Here is a Sandbox for you to demonstrate the idea: https://codesandbox.io/s/dark-framework-xuhxn?file=/src/App.js

React crashes without displaying error when user selects one option but then changes it to another option

My code is working when a user selects any of the options.
However, when they select the 'now' option and then change their mind and select the 'specific' option, React crashes without displaying an error - it just shows a white screen.
This problem doesn't occur when the options are selected the other way round - when 'specific' is selected and the user changes their mind and selects 'now'.
When 'specific' is selected a new input is rendered.
A simplified version of the code is below:
render() {
let startSelling = values.tickets.map((e,i) => {
if(e.startSelling == 'specific'){
return(
<div>
<DatePicker
className="datePicker"
timeIntervals={15}
onChange={event => this.props.setSpecificTime(event, i, 'startSellingTime', values)}
selected={values.tickets[i].startSellingTime}
placeholderText='Select Date And Time'
showTimeSelect
dateFormat="Pp"
/>
</div>
)
}else{return <div></div>}
})
return (
<>
{this.state.tickets.map((e, i) => {
return (
<div>
<div>
<select
value={values.tickets[i].startSelling}
onChange={event => this.props.changeSellingTimes(event, i, 'startSelling', 'startSellingTime', values)}
>
<option value='' disabled>Start Selling Tickets</option>
<option value="now">Now</option>
<option value="specific">Specific Date and Time</option>
{i===1 ? <option value="whenPreviousSoldOut">When {values.tickets[0].ticketType} Is Sold Out</option>:<option value="whenPreviousSoldOut" disabled={i==0}>When A Previous Ticket Is Sold Out</option>}
</select>
</div>
{startSelling[i]}
</div>
)
})}
</>
)
}
Where am I going wrong?
Found it. Selecting 'now' was saving a date as a moment object in state. Datepicker caused react to crash when it tried to read it.

Keep selected value in a set group of radio buttons in React

I have different groups of radio button within a form on this way:
<form onSubmit={handleSubmit}>
{FormData.map(formDetails => {
return (
<div className='form-options' key={formDetails.id}>
<h2 className='form-option__title'>{formDetails.title}</h2>
<p className='form-option__description'>
{formDetails.description}
</p>
<fieldset>
{formDetails.options.map(formOptions => {
const getScore = e => {
setCheck(formOptions.id);
if (typeof formOptions.value === 'string') {
setScore(0);
} else {
setScore(e.target.value);
}
};
return (
<RadioOption
key={formOptions.id}
htmlFor={formOptions.id}
type='radio'
id={formOptions.id}
name={formOptions.name}
value={formOptions.value}
onChange={getScore}
checked={check === formOptions.id}
/>
);
})}
</fieldset>
</div>
);
})}
...
</form>
What happens is that when I select a radio option in a different fieldset, it doesn't keep the option selected in the previous one.
Found the solution. The main mistake was on the name attribute, each radio button had a different name. Changed it to be the same within the group, and working. Also updated the onChange function and created different components.

How to filter data based on selected value from dropdown menu and search query in input field using reactjs?

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.

Render all options in typeahead menu when item is selected

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

Resources