Can we remove one of selected option in react-select programmatically? - react-select

In react-select https://github.com/jedwatson/react-select , can we remove one of selected option in react-select programmatically?
E.g in the below screenshot I would like to unselectred programmatically?
Many thanks!

You can save selected options in state and remove selected one by update new state, you can check here codeSandBox
import React, { useState } from "react";
import "./styles.css";
import Select from "react-select";
const options = [
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
];
export default function App() {
const [selectedOption, setSelect] = useState(null);
const handleChange = selectedOption => {
setSelect(selectedOption);
};
const removeOption = e => {
const newSelect = selectedOption.filter(
item => item.value !== e.target.name
);
setSelect(newSelect);
};
return (
<>
<Select
isMulti
value={selectedOption}
onChange={handleChange}
options={options}
/>
<button name="chocolate" onClick={removeOption}>
Remove Chocolate
</button>
<button name="vanilla" onClick={removeOption}>
Remove Vanilla
</button>
<button name="strawberry" onClick={removeOption}>
Remove Strawberry
</button>
</>
);
}

Related

Can react-select underline searched text in filtered options?

I want to create react-select that when user type text, it will show filtered options whose part of match texts are underlined and change color from black to red as provided below image. Is it possible? Thanks.
After a while, I get the answer :)
import Select, { components } from 'react-select';
const options1 = [
{
value: 'chocolate',
label: 'chocolate',
},
{
value: 'strawberry',
label: 'strawberry',
},
{
value: 'vanilla',
label: 'vanilla'
}
]
class MyOption extends React.Component {
f_search = (input,option) => {
const num = option.indexOf(input)
const len = input.length
return (
<div>
<span>{option.substr(0, num)}</span>
<span style={{color:"red", textDecoration: "underline"}}>{input}</span>
<span>{option.substr(num +len)}</span>
</div>
)
}
render() {
const input = this.props.selectProps.inputValue
const option = this.props.data.label
return (
<components.Option {...this.props}>
{this.f_search(input,option)}
</components.Option>
)
}
}
const ReactSelect7 = () =>
<Select options={options1} components={{ Option: MyOption }} />

React Admin: how to pass state to transform

I have a component for creating media which uploads the media first to S3, then puts the returned values into the component's state:
import { Create, ReferenceInput, SelectInput, SimpleForm, TextInput } from 'react-admin';
import { Field } from 'react-final-form';
import React, { useState } from 'react';
import { ImageHandler } from './ImageHandler';
import { BeatLoader } from 'react-spinners';
export const MediaCreate = props => {
const [image, setImage] = useState(null);
const [isUploading, setIsUploading] = useState(false);
console.log(image) // <-- this contains the image object after uploading
const transform = data => {
console.log(image) // <-- this is NULL after clicking submit
return {
...data,
key: image.key,
mime_type: image.mime
}
};
return (
<Create {...props} transform={transform}>
<SimpleForm>
<SelectInput source="collection" label="Type" choices={[
{ id: 'gallery', name: 'Gallery' },
{ id: 'attachment', name: 'Attachment' },
]}/>
<ReferenceInput label="Asset" source="asset_id" reference="assets">
<SelectInput optionText="name"/>
</ReferenceInput>
<TextInput source={'name'} />
{isUploading &&
<div style={{ display: 'flex', alignItems: 'center' }}>
<BeatLoader
size={10}
color={"#123abc"}
loading={isUploading}
/> Uploading, please wait
</div>
}
<ImageHandler
isUploading={(isUploading) => setIsUploading(isUploading)}
onUploaded={(image) => setImage(image)}
/>
</SimpleForm>
</Create>
);
};
Why is image null despite containing the value after upload? How can I pass in my component state to the transform function?
This can be reached by useRef
export const MediaCreate = props => {
const [image, setImage] = useState(null);
const [isUploading, setIsUploading] = useState(false);
const someRef = useRef()
someRef.current = image
const transform = data => {
console.log(someRef.current) // <-- this will not be NULL
return {
...data,
key: someRef.current.key,
mime_type: someRef.current.mime
}
};

MobX observable changes not updating components

I have a store in MobX that handles containing the cart, and adding items to it. However, when that data is updated the components don't re-render to suit the changes.
I tried using useEffect to set the total price, however when the cartData changes, the state is not updated. It does work on mount, though.
In another component, I call addItemToCart, and the console.warn function returns the proper data - but that data doesn't seem to be synced to the component. clearCart also seems to not work.
My stores are contained in one RootStore.
import React, {useState, useEffect} from 'react';
import {List, Text} from '#ui-kitten/components';
import {CartItem} from '_molecules/CartItem';
import {inject, observer} from 'mobx-react';
const CartList = (props) => {
const {cartData} = props.store.cartStore;
const [totalPrice, setTotalPrice] = useState(0);
const renderCartItem = ({item, index}) => (
<CartItem itemData={item} key={index} />
);
useEffect(() => {
setTotalPrice(cartData.reduce((a, v) => a + v.price * v.quantity, 0));
console.warn('cart changed!');
}, [cartData]);
return (
<>
<List
data={cartData}
renderItem={renderCartItem}
style={{backgroundColor: null, width: '100%'}}
/>
<Text style={{textAlign: 'right'}} category={'s1'}>
{`Total $${totalPrice}`}
</Text>
</>
);
};
export default inject('store')(observer(CartList));
import {decorate, observable, action} from 'mobx';
class CartStore {
cartData = [];
addItemToCart = (itemData) => {
this.cartData.push({
title: itemData.title,
price: itemData.price,
quantity: 1,
id: itemData.id,
});
console.warn(this.cartData);
};
clearCart = () => {
this.cartData = [];
};
}
decorate(CartStore, {
cartData: observable,
addItemToCart: action,
clearCart: action,
});
export default new CartStore();
I have solved the issue by replacing my addItemToCart action in my CartStore with this:
addItemToCart = (itemData) => {
this.cartData = [
...this.cartData,
{
title: itemData.title,
price: itemData.price,
quantity: 1,
id: itemData.id,
},
];
console.warn(this.cartData);
};

React Native State is Undefined Vasern

I am actually starting with Mobile Development and React Native and I thought an interesting Database called Vasern But now I am trying to load things from my database with the componentDidMount() method but i actually just get this Error everytime.
I am sure its just a trivial Error but i just cant find it...
Thanks in Advance
import React, {Component} from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
Button,
SectionList
} from 'react-native';
import Vasern from 'vasern';
import styles from './styles';
const TestSchema = {
name: "Tests",
props: {
name: "string"
}
}
const VasernDB = new Vasern({
schemas: [TestSchema],
version: 1
})
const { Tests } = VasernDB;
var testList = Tests.data();
class Main extends Component {
state = {
tests: [],
};
constructor(props){
super(props);
this._onPressButton = this._onPressButton.bind(this);
this._onPressPush = this._onPressPush.bind(this);
this._onPressUpdate = this._onPressUpdate.bind(this);
this._onPressDeleteAll = this._onPressDeleteAll.bind(this);
}
componentDidMount() {
Tests.onLoaded(() => this._onPressButton());
Tests.onChange(() => this._onPressButton());
}
_onPressButton = () => {
let tests = Tests.data();
console.log(tests);
//if( tests !== undefined){
this.setState({tests}); // here is the error
//alert(tests);
//}
}
_onPressPush = () => {
Tests.insert({
name: "test"
});
console.log(this.state.tests + "state tests"); //here the console only shows the text
}
_onPressUpdate = () => {
var item1 = Tests.get();
Tests.update(item1.id, {name: "test2"});
}
_onPressDelete = () => {
}
_onPressDeleteAll = () => {
let tests = Tests.data();
tests.forEach((item, i) => {
Tests.remove(item.id)
});
}
_renderHeaderItem({ section }) {
return this._renderItem({ item: section});
}
_renderItem({ item }){
return <View><Text>{item.name}</Text></View>
}
render() {
//const { tests = [] } = this.props;
return (
<View style={styles.container}>
<View>
<TextInput> Placeholder </TextInput>
<Button title="Press me for Show" onPress={this._onPressButton}/>
<Button title="Press me for Push" onPress={this._onPressPush}/>
<Button title="Press me for Update" onPress={this._onPressUpdate}/>
<Button title="Press me for Delete" onPress={this._onPressDelete}/>
<Button title="Press me for Delete All" onPress={this._onPressDeleteAll}/>
</View>
<View style={styles.Input}>
<SectionList
style={styles.list}
sections={this.state.tests}
keyExtractor={item => item.id}
renderSectionHeader={this._renderHeaderItem}
contentInset={{ bottom: 30 }}
ListEmptyComponent={<Text style={styles.note}>List Empty</Text>}
/>
</View>
</View>
);
}
}
export default Main;
Since Tests.data() will return an array (as list of records).
In React Native, you might use FlatList to display an array of records.
import { ..., FlatList } from 'react-native';
...
// replace with SectionList
<FlatList
renderItem={this._renderItem} // item view
data={this.state.tests} // data array
style={styles.list}
keyExtractor={item => item.id}
contentInset={{ bottom: 30 }}
ListEmptyComponent={<Text style={styles.note}>List Empty</Text>}
/>
In case you want to use SectionList, you will need to reform data into sections. Something like:
var sections = [
{title: 'Title1', data: ['item1', 'item2']},
{title: 'Title2', data: ['item3', 'item4']},
{title: 'Title3', data: ['item5', 'item6']},
]
Besides, React Native is in a really good state. I think you will like it.

get active tab from Closable TabPanel in extReact sencha component

I'm making Closable TabPanel and at the moment when I click on the certain tab I will switch to the Panel of that's tab. What Panel's tab I click, that Panel opens. That's great.
but now I want to have a carousel button on the side, to list next, next, next Panel.
Which means I need to know on what panel I am at the moment (what panel is active now)? And How to tell take next panel in the row ( setPanel(activeId+1) ) ?
For now, I'm getting a list of all existing PANELS and I extract all their IDs: [45,46,47,48,49]. I'm getting it form DataBase, but I don't know how to get currently Active panel and how to say go to next!?
Any ideas?
use property: activeItem={2}
for example: <TabPanel activeItem={this.state.componentNumber} border={false} ...> </TabPanel>
App.js
import React, { Component } from 'react';
import { Button } from '#extjs/ext-react';
import ClosableComponent from './ClosableComponent';
class App extends Component {
constructor() {
super();
this.state = {
componentNumber: 2,
};
}
switchFunctionLeft = () => {
if(this.state.componentNumber === 0){
this.setState({ componentNumber: 2 })
}else{
this.setState({ componentNumber: this.state.componentNumber - 1 })
}
}
switchFunctionRight = () => {
if(this.state.componentNumber === 2){
this.setState({ componentNumber: 0 })
}else{
this.setState({ componentNumber: this.state.componentNumber + 1 })
}
}
render() {
return (
<div className="App">
<div >
<ClosableComponent componentNumber={this.state.componentNumber} />
<Button text="switch to left" handler={this.switchFunctionLeft} />
<Button text="switch to right" handler={this.switchFunctionRight}/>
</div>
</div>
);
}
}
export default App;
ClosableComponent.js
import React, {
Component
} from 'react';
import {
TabPanel,
Container,
Toolbar,
Button
} from '#extjs/ext-react';
class ClosableComponent extends Component {
nextKey = 0;
constructor() {
super();
this.state = {
type: "No",
switch: "",
tabs: [
this.nextKey++,
this.nextKey++,
this.nextKey++
]
};
}
onCloseTab = tab => {
const tabs = this.state.tabs.filter(t => t !== tab);
this.setState({
tabs
})
}
addTab = () => {
const key = this.nextKey++;
const tabs = [...this.state.tabs, key];
this.setState({tabs})
this.tabPanel.setActiveItem(tabs.indexOf(2))
return false;
}
render() {
const { tabs } = this.state;
return (
<div>
<Container layout="fit" padding = {10}>
<TabPanel
ref = {tp => this.tabPanel = tp}
_reactorIgnoreOrder
shadow
style={{ backgroundColor: 'white', "height": "200px"}}
activeItem={this.props.componentNumber}
tabBar={{
height: 48,
layout: {
pack: 'left'
},
style: {
paddingRight: '52px'
}
}}
>
{ tabs.map(key => (
<Container
title = {`Tab ${key}`}
tab = {{ flex: 1, maxWidth: 150 }}
key = {key}
layout = "center"
closable
onDestroy = {this.onCloseTab.bind(this, key)}
>
<div style = {{ whiteSpace: 'nowrap' }}>Tab {key} Content</div>
</Container>
))}
</TabPanel>
<Button
top={18}
right={20}
iconCls="x-fa fa-plus"
handler={this.addTab}
ui="alt round"
tooltip="New Tab"
/>
</Container>
</div>
);
}
}
export default ClosableComponent;