Following their example I am trying to get the selected value to dispatch it after that to my action but can't find any way to get it. Any help?
import React, { Component } from 'react';
import { Dropdown } from 'react-native-material-dropdown';
class Example extends Component {
constructor(props) {
super(props)
this.state = {
category: undefined,
}
}
onPost = () => {
var { category } = this.state;
console.log(category) // Undefined
}
render() {
let category = [{
value: 'Banana',
}, {
value: 'Mango',
}, {
value: 'Pear',
}];
return (
<Dropdown
label='Favorite Fruit'
data={category}
/>
<TouchableOpacity onPress={this.onPost}>
<FontAwesome name="check" size={25} color="white" />
</TouchableOpacity>
);
}
}
You can use onChangeText method to get the currently selected value. You can also send it via props to a handler method and use it as your app needs.
Example:
render() {
(...)
<Dropdown
label='Favorite Fruit'
data={category}
onChangeText(value => this.onChangeHandler(value)}
/>
(...)
}
const onChangeHandler = (value) => {
console.log(`Selected value: ${value}`);
}
Hope it helps
Related
I'm trying to pass props from my Rails database to a React Select component using React rails, but the text is appearing invisible within the select option.
View:
= react_component('SelectSearch', options: Course.all.as_json(only: [:title]))
React select component:
import React from 'react';
import Select from 'react-select';
class SelectSearch extends React.Component {
constructor(props) {
super(props)
}
state = {
selectedOption: null,
};
handleChange = selectedOption => {
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
};
render() {
const { selectedOption } = this.state;
return (
<Select
value={selectedOption}
onChange={this.handleChange}
options={this.props.options}
/>
);
}
}
export default SelectSearch;
When something in the select is clicked, it console logs, for example:
Option selected: {title: "English"}
But opening the select, its completely blank. There is obviously an option there that can be clicked, but nothing is displayed. Likewise for searching, no options are displayed.
I know this is because I'm passing the props incorrectly, or handling the data incorrectly, I don't want {title: "English"} I just want English but not sure how to filter this correctly.
See the react-select example:
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
]
const MyComponent = () => (
<Select options={options} />
)
Your options contains unneeded 'title' attribute and not contains 'value' and 'label'. Fix it.
Took me a while to figure it out, but got this working:
= react_component('SelectSearch', data: Course.all.as_json(only: [:title]))
import React from 'react';
import Select from 'react-select';
class SelectSearch extends React.Component {
constructor(props) {
super(props);
}
state = {
selectedOption: null,
};
handleChange = selectedOption => {
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
};
render() {
const { selectedOption } = this.state;
return (
<Select
value={selectedOption}
onChange={this.handleChange}
options={this.props.data}
getOptionLabel={(option) => option.title}
getOptionValue={(option) => option.title}
/>
);
}
}
export default SelectSearch;
React-select expects a value and a label and this seems to be the easiest way to pass it.
I am using the react-select library with a list of states, and then using that to hide/show my elements
The elements are showing when I select them from the list, but then don't hide when they're removed. Here is the code:
import React from 'react';
import Select from 'react-select';
const options = [
{ value: 'ny', label: 'NY' },
{ value: 'ca', label: 'California' },
{ value: 'ak', label: 'Arkansas' }
];
export default class HomePage extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
handleChange = (selectedOption) => {
if (!selectedOption) {
this.setState({})
}
else {
const result = {}
selectedOption.map((option) => {
result[option.value] = true
})
this.setState(result)
}
}
render() {
return (
<div>
<Select
isMulti
onChange={this.handleChange}
options={options}
/>
{this.state.ny && (
<div>NY State Images</div>
)}
{this.state.ca && (
<div>CA State Images</div>
)}
{this.state.ak && (
<div>AK State Images</div>
)}
</div>
)
}
}
Something is strange with that React.Component.
Try to use functional component:
export default function HomePage() {
const [state, setState] = useState({});
const handleChange = selectedOption => {
console.log("CHANGE_HAPPEN: ", selectedOption);
if (!selectedOption) {
setState({});
} else {
const result = {};
selectedOption.forEach(option => {
result[option.value] = true;
});
console.log("RESULT: ", result);
setState(prev => result);
}
};
return (
<div>
<Select isMulti onChange={handleChange} options={options} />
{state.ny && <div>NY State Images</div>}
{state.ca && <div>CA State Images</div>}
{state.ak && <div>AK State Images</div>}
</div>
);
}
I want to make sets of buttons as many as the number of rooms
So I used a map to make radio button sets
If it works there should be 4 sets of buttons.
but it doesn't work
please help
import React, { Component } from "react";
import { Text, View } from "react-native";
import RadioForm, {
RadioButton,
RadioButtonInput,
RadioButtonLabel
} from "react-native-simple-radio-button";
const temp_data = {
room1: 0.1,
room2: 0.2,
room3: 0.3,
room4: 0.4
};
var radio_props = [{ label: "10%", value: 0 }, { label: "30%", value: 1 }];
export default class TaskSetting extends Component {
render() {
var tem1 = Object.keys(temp_data).map(num => {
return;
<RadioForm
radio_props={radio_props}
initial={0}
onPress={value => {
this.setState({ value: value });
}}
/>;
});
return <View>{tem1}</View>;
}
}
If you use => {}, you need to add return <YourComponent /> inside {},
or you can choose not to use {} and directly => <YourComponent />
export default class TaskSetting extends Component {
render() {
return (
<View>
{Object.keys(temp_data).map(num =>
<RadioForm
radio_props={radio_props}
initial={0}
onPress={value => {
this.setState({ value: value });
}}
/>
)}
</View>
)
}
}
Check it online:
I have a lot of hits, which I want to add to an array once a hit is pressed. However, as far as I observed, the array looked like it got the name of the hit, which is the value. The value was gone in like half second.
I have tried the methods like building constructor, and doing things like
onClick={e => this.handleSelect(e)}
value={hit.name}
onClick={this.handleSelect.bind(this)}
value={hit.name}
onClick={this.handleSelect.bind(this)}
defaultValue={hit.name}
and so on
export default class Tagsearch extends Component {
constructor(props) {
super(props);
this.state = {
dropDownOpen:false,
text:"",
tags:[]
};
this.handleRemoveItem = this.handleRemoveItem.bind(this);
this.handleSelect = this.handleSelect.bind(this);
this.handleTextChange = this.handleTextChange.bind(this);
}
handleSelect = (e) => {
this.setState(
{ tags:[...this.state.tags, e.target.value]
});
}
render() {
const HitComponent = ({ hit }) => {
return (
<div className="infos">
<button
className="d-inline-flex p-2"
onClick={e => this.handleSelect(e)}
value={hit.name}
>
<Highlight attribute="name" hit={hit} />
</button>
</div>
);
}
const MyHits = connectHits(({ hits }) => {
const hs = hits.map(hit => <HitComponent key={hit.objectID} hit={hit}/>);
return <div id="hits">{hs}</div>;
})
return (
<InstantSearch
appId="JZR96HCCHL"
apiKey="b6fb26478563473aa77c0930824eb913"
indexName="tags"
>
<CustomSearchBox />
{result}
</InstantSearch>
)
}
}
Basically, what I want is to pass the name of the hit component to handleSelect method once the corresponding button is pressed.
You can simply pass the hit.name value into the arrow function.
Full working code example (simple paste into codesandbox.io):
import React from "react";
import ReactDOM from "react-dom";
const HitComponent = ({ hit, handleSelect }) => {
return <button onClick={() => handleSelect(hit)}>{hit.name}</button>;
};
class Tagsearch extends React.Component {
constructor(props) {
super(props);
this.state = {
tags: []
};
}
handleSelect = value => {
this.setState(prevState => {
return { tags: [...prevState.tags, value] };
});
};
render() {
const hitList = this.props.hitList;
return hitList.map(hit => (
<HitComponent key={hit.id} hit={hit} handleSelect={this.handleSelect} />
));
}
}
function App() {
return (
<div className="App">
<Tagsearch
hitList={[
{ id: 1, name: "First" },
{ id: 2, name: "Second" },
{ id: 3, name: "Third" }
]}
/>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
additionally:
note the use of prevState! This is a best practice when modifying state. You can google as to why!
you should define the HitComponent component outside of the render method. it doesn't need to be redefined each time the component is rendered!
I use the dropdown in react js app but onChange is not triggering
my code is
import React from "react";
import PropTypes from "prop-types";
import Dropdown from 'react-dropdown';
const options = [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two', className: 'myOptionClassName' },
];
class WebDashboardPage extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
quan = (event)=> {
console.log("Option selected:");
this.setState({ value: event.target.value });
};
render() {
return(
<b><Dropdown className="dropdownCss" options={options} onChange={e =>
this.quan(e.target.value)} /></b>
);
}
when I click the items in dropdown it shows the error
"TypeError: Cannot read property 'quan' of undefined"
I'm a newbie to react
thanks in advance
There is no issue with the react-dropdown library. Here is the code sandbox that I've set up and corrected OP's code. It works.
import React from "react";
import Dropdown from "react-dropdown";
import "react-dropdown/style.css";
const options = [
{ value: "one", label: "One" },
{ value: "two", label: "Two", className: "myOptionClassName" }
];
const defaultOption = options[0];
class WebDashboardPage extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedValue: ""
};
}
quan = value => {
this.setState({ selectedValue: value });
};
render() {
return (
<Dropdown options={options} value={defaultOption} onChange={this.quan} />
);
}
}
export default WebDashboardPage;
You should just do it this way:
<Dropdown className="dropdownCss" options={options} onChange={this.quan} />
Try this:
class WebDashboardPage extends React.Component {
constructor(props) {
super(props);
this.state = { value: '' }
this.quan = this.quan.bind(this);
}
quan(event) {
console.log("Option selected:");
this.setState({ value: event.target.value });
};
render() {
return(
<div><Dropdown className="dropdownCss" options={options} onChange={this.quan} /></div>
);
}
It seems the issue is with the react-dropdown component itself. You'll need to file an issue there.
react-dropdown component might not be using this.props.onChange somewhere or might be using problematically.
Or, it's probably, the component requires value state which have not defined?
this.state = {
value: ''
}
And was causing the issue?
The dropdown dependency you are using does not fire onChange with event as argument instead it fires onChange with the selected option.Try changing
onChange={e =>
this.quan(e.target.value)}
to
onChange={this.quan}
and change quan to
quan = (selectedOption)=> {
console.log("Option selected:"+selectedOption.value);
this.setState({ value: selectedOption.value });
};
I have tried it on my machine and it wroks perfectly. Also next important thing is don't put options the way you are doing instead put it on state. my final code is
class WebDashboardPage extends Component {
constructor(props) {
super(props);
const options = [
{
value: 'one',
label: 'One'
}, {
value: 'two',
label: 'Two',
className: 'myOptionClassName'
}
];
this.state = {options}
}
quan = (selectedOption) => {
console.log("Option selected:" + selectedOption.value);
this.setState({value: selectedOption.value});
};
render() {
return (<b><Dropdown className="dropdownCss" options={this.state.options} onChange={this.quan}/></b>);
}
}
I only did a little refactoring to the code. The main change is in how Dropdown handles change. When you pass in a function to handleChange, Dropdown calls the function internally and passes the selected object to it, so you all you needed to do was create a handler method that has one parameter which you'll use to update the state. I also set an initial state for value. Here's is a demo https://codesandbox.io/s/4qz7n0okyw
import React, { Component, Fragment } from "react";
import ReactDOM from "react-dom";
import Dropdown from "react-dropdown";
const options = [
{ value: "one", label: "One" },
{ value: "two", label: "Two", className: "myOptionClassName" }
];
class WebDashboardPage extends Component {
state = {
value: {}
};
quan = value => {
console.log("Option selected:", value);
this.setState({ value });
};
render() {
return (
<Fragment>
<Dropdown
className="dropdownCss"
options={options}
onChange={this.quan}
/>
</Fragment>
);
}
}
export default WebDashboardPage;
Change to
onChange={this.quan}, also in the initial state you should state your this.state.value
this.state = {
value: ''
}
also try to learn it on html element, not on jsx