I have 'textRef' created in parent component and passed to children component using createRef().
I am trying to dynamically focus Input in children component on props change.
It does work when I test on localhost (chrome) but not on web view.
Any advice on this issue ?
Thanks !!
parent component
const UserAddressForm = ({ query }) => {
const textRef = useRef(null);
const {
state: { newAddress },
saveMultiData,
} = query;
useEffect(() => {
if (textRef && textRef.current) {
textRef.current.focus();
}
}, [newAddress.zipcode]);
const onAddressChange = (type, value) => {
const addressObj = {
...newAddress,
};
...
saveMultiData({ newAddress: addressObj });
};
return (
<InfoUl margin="21px 0px 0px;">
...
<TextField
ref={textRef}
label=""
name="addr2"
placeholder="상세주소 입력"
textField={newAddress}
onInputChange={e => onAddressChange('addr2', e.target.value)}
/>
</InfoUl>
);
};
children component
import React from 'react';
import PropTypes from 'prop-types';
import { LabelBox, InputBox } from './styles';
const TextField = React.forwardRef(
(
{
label = null,
name,
type,
placeholder,
textField,
onInputChange,
autoComplete,
pattern,
disabled,
width,
flex,
marginRight,
marginBottom,
},
ref,
) => (
<LabelBox width={width} marginBottom={marginBottom}>
{label !== null && <label htmlFor={label}>{label}</label>}
<InputBox flex={flex} marginRight={marginRight}>
<input
ref={ref}
type={type || 'text'}
name={name}
placeholder={placeholder}
value={textField[name] || ''}
onChange={onInputChange}
autoComplete={autoComplete || 'on'}
pattern={pattern || null}
disabled={!!disabled}
/>
</InputBox>
</LabelBox>
),
);
version
React v16.9.0
I resolved it by using input autoFocus attribute as well as ref attribute.
Since input appears dynamically on a button click, ref.focus won't work.
AutoFocus will get focus when the input appears.
Then Ref will get re-focus where the input is already placed on address re-search.
Related
I'm trying to set the state from the parent component using a callback. This callback gets passed down to the child component that renders a material ui datatable. The callback responds onClick and passes some values to the callback. The problem is that setting the state with the values from the callback arguments doesn't work.
My assumption is that when the user clicks the button from the child component, it should invoke the callback function and pass the values I needed to set the state.
Parent Component:
export default function ViewJobs() {
const [type, setType] = useState('');
const [params, setParams] = useState({});
const callback = ({ cellValues, componentType, path }) => {
setType(componentType);
setParams(cellValues) // Sets the params with an object.
console.log(cellValues) // Displays the data I need in the console
history.push(path);
};
console.log(params) // Displays undefine in the console.
return(
<React.Fragment>
<TabPanel value={value} index={0} dir={theme.direction} >
<DataTable
jobs={job}
title='All'
parentCallback={callback}
/>
</TabPanel>
</React.Fragment>
);
}
Child Component
import React, { useEffect } from 'react';
export default function DataTable(props) {
const { jobs, parentCallback } = props;
const rows = jobs.payload;
const handleDiaryClick = (event, cellValues) => {
const params = {
cellValues,
componentType: 'diary',
path: "/view/jobs/diary"
};
parentCallback(params);
};
const renderDiaryElement = params => {
return (
<Button
variant="contained"
color="primary"
style={{ backgroundColor: "#000000" }}
onClick={(event) => {
handleDiaryClick(event, params);
}}
>
<MenuBookIcon />
</Button>
);
}
return (
<div
className={classes.root}
style={{ height: 400, width: '100%' }}
>
<DataGrid
rows={rows}
columns={columns}
pageSize={5}
//checkboxSelection
disableSelectionOnClick
/>
</div>
);
}
Since the state has been lifted up to the parent component, I'm under the impression that the code above should be working.
I tried to reproduce the issue but I couldn't replicate it.
Any advice or inputs are appreciated. Thanks.
After further checking on my codebase, I found that the history.push(path) located in my callback is causing the issue. I had to remove this line of code for it to work.
The issue is keydown/keyup aren't working when mention list popup has scroll , i can scroll using mouse but keyup/keydown aren't making the scroll move to the right position
This can be achieved by custom entry Component ->
const entryComponent = (props:any) => {
const { mention, isFocused, searchValue, ...parentProps } = props;
const entryRef = React.useRef<HTMLDivElement>(null);
useEffect(() => {
if (isFocused) {
if (entryRef.current && entryRef.current.parentElement) {
entryRef.current.scrollIntoView({
block: 'nearest',
inline: 'center',
behavior: 'auto'
});
}}
}, [isFocused]);
return (
<>
<div
ref={entryRef}
role='option'
aria-selected={(isFocused ? 'true' : 'false')}
{...parentProps}>
<div className={'mentionStyle'}>
{mention.name}
</div>
</div>
</> );
};
In my React Native application, I use React Navigation.
It's an app that enables the user to search an underlying database, i.e. for names. The GIF below illustrates the navigation.
From the landing screen, Go to search button is pressed (Main Stack Navigator) --> The Header appears, which is alright.
On the second screen, there is a bottomTabNavigator, where names is chosen (in names, there is a second StackNavigator nested).
This leads to the third screen. Here, three cards are shown. With the help of the second StackNavigator, clicking on Mehr opens a details screen.
What I want to achieve is that the Header of the first StackNavigator (that one at the top) disappears as soon as the user opens the details screen.
You see a button there because in the first step, I wanted to let the Header disappear on button click.
The below code works if it is implemented in a screen that is derived from the first StackNavigator directly. But because I am inside a nested navigator, it does not work anymore.
Here is the code:
App.tsx:
imports ...
class RootComponent extends React.Component {
render() {
const image = require('./assets/images/corrieBackground3.png');
console.log('calling the store', this.props.resultValue); // undefined
return (
<View style={styles.container}>
<LandingPage />
</View>
);
}
}
const RootStack = createStackNavigator(
{
LandingPage: {
screen: RootComponent,
navigationOptions: {
header: null,
},
},
SearchScreen: {
screen: SearchScreen,
navigationOptions: {
title: 'I SHOULD DISAPPEAR',
},
},
},
{
initialRouteName: 'LandingPage',
},
);
const AppContainer = createAppContainer(RootStack);
export default class App extends React.Component {
render() {
return <AppContainer />;
}
}
TwoTabs.tsx (for the 2nd screen):
imports ...
const SearchBarStack = createStackNavigator(
{
SearchBar: {
screen: SearchBar,
navigationOptions: {
header: null,
},
},
Details: {
screen: Details,
navigationOptions: {
title: 'I am here, above header disapear',
},
},
},
{
initialRouteName: 'SearchBar',
},
);
const TabNavigator = createBottomTabNavigator(
{
One: {
screen: SearchCriteria,
navigationOptions: {
tabBarLabel: 'criteria',
},
},
Two: {
screen: SearchBarStack,
navigationOptions: {
tabBarLabel: 'names',
},
},
},
);
const TabLayout = createAppContainer(TabNavigator);
type Props = {};
const TwoTabsHorizontal: React.FC<Props> = ({}) => {
return (
<View>
<TabLayout />
</View>
);
};
export default TwoTabs;
SearchBar.tsx (3rd screens skeleton):
import ...
type Props = {};
const SearchBar: React.FC<Props> = () => {
// logic to perform database query
return (
<View>
<ScrollView>
... logic
<SearchResult></SearchResult> // component that renders 3 cards
</ScrollView>
</View>
);
};
export default SearchBar;
Card.tsx (card rendered by SearchResult):
imports ...
type Props = {
title: string;
navigation: any;
};
const Card: React.FC<Props> = ({title, navigation}) => {
return (
<Content>
<Card>
<CardItem>
<Right>
<Button
transparent
onPress={() => navigation.navigate('Details')}>
<Text>Mehr</Text>
</Button>
</Right>
</CardItem>
</Card>
</Content>
);
};
export default withNavigation(Card);
And finally, the Details screen together with its Content. Here, the Header from the first StackNavigator should be hidden.
imports ...
type Props = {};
const Details: React.FC<Props> = ({}) => {
return (
<View>
<Content></Content>
</View>
);
};
export default Details;
imports ...
type Props = {
navigation: any;
};
class Content extends React.Component {
state = {
showHeader: false,
};
static navigationOptions = ({navigation}) => {
const {params} = navigation.state;
return params;
};
hideHeader = (hide: boolean) => {
this.props.navigation.setParams({
headerShown: !hide,
});
console.log('props ', this.props.navigation);
};
render() {
return (
<View>
<View>
</View>
<Button
title={'Press me and the header will disappear!'}
onPress={() => {
this.setState({showHeader: !this.state.showHeader}, () =>
this.hideHeader(this.state.showHeader),
);
}}
/>
</View>
);
}
}
export default withNavigation(CardExtended);
Maybe someone has an idea?
I am having a very weird bug. I have reproduced the simplest test case scenario here: https://codesandbox.io/s/PNyPwyWP2
I have also uploaded a screencast explaining, the screencast is on youtube here - https://youtu.be/iILiFieO-gk
My goal is that I have a form with a single field, a button "Reset" and a button "Save". Clicking "Save" saves the form values into a reducer in my store called save. Clicking "Reset" should reset the form values to the last "pristine" values (the values in initialValues).
However my issue is, after saving the form, the "Reset" button should reset it to the "pristine" value (the newly saved value, the value in initialValues) but it is reseting it to the "old pristine value"
Here is my full app code:
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { createStore, combineReducers } from 'redux'
import { connect } from 'react-redux'
import { Field, reduxForm, reducer as form } from 'redux-form'
// ACTION & ACTION CREATOR
const SAVE_FORM = 'SAVE_FORM';
function saveForm(values) {
return {
type: SAVE_FORM,
values
}
}
// REDUCER - save
const INITIAL = { url:'hiiii' };
function save(state=INITIAL, action) {
switch(action.type) {
case SAVE_FORM: return action.values;
default: return state;
}
}
// STORE
const reducers = combineReducers({ form, save });
const store = createStore(reducers);
// MY FORM COMPONENT
class MyFormDumb extends React.Component {
handleReset = e => {
e.preventDefault();
this.props.reset();
}
render() {
console.log('MyFormDumb :: pristine:', this.props.pristine, 'initialValues:', this.props.initialValues);
return (
<form onSubmit={this.props.handleSubmit}>
<label htmlFor="url">URL</label>
<Field name="url" component="input" type="text" />
<button onClick={this.handleReset}>Reset</button>
<button type="submit">Save</button>
</form>
)
}
}
const MyFormControlled = reduxForm({ form:'my-form' });
const MyFormSmart = connect(
function(state) {
return {
initialValues: state.save
}
}
);
const MyForm = MyFormSmart(MyFormControlled(MyFormDumb));
// MY APP COMPONENT
class App extends React.PureComponent {
submitHandler = (values, dispatch, formProps) => {
dispatch(saveForm(values));
}
render() {
return (
<Provider store={store}>
<div className="app">
<MyForm onSubmit={this.submitHandler} />
</div>
</Provider>
)
}
}
// RENDER
ReactDOM.render(<App />, document.getElementById('app'))
Please use enableReinitialize: true flag on your reduxForm component, as per the docs.
I'm using React-Bootstrap Popover and I was wondering if there is any builtin property that I can add either to Popover itself or to OverlayTrigger so only one popover will display at a time.
You can try rootClose props which will trigger onHide when the user clicks outside the overlay. Please note that in this case onHide is mandatory. e.g:
const Example = React.createClass({
getInitialState() {
return { show: true };
},
toggle() {
this.setState({ show: !this.state.show });
},
render() {
return (
<div style={{ height: 100, position: 'relative' }}>
<Button ref="target" onClick={this.toggle}>
I am an Overlay target
</Button>
<Overlay
show={this.state.show}
onHide={() => this.setState({ show: false })}
placement="right"
container={this}
target={() => ReactDOM.findDOMNode(this.refs.target)}
rootClose
>
<CustomPopover />
</Overlay>
</div>
);
},
});
I managed to do this in a somewhat unconventional manner. You can create a class which tracks the handlers of all of your tooltips:
export class ToolTipController {
showHandlers = [];
addShowHandler = (handler) => {
this.showHandlers.push(handler);
};
setShowHandlerTrue = (handler) => {
this.showHandlers.forEach((showHandler) => {
if (showHandler !== handler) {
showHandler(false);
}
});
handler(true);
};
}
Then in your tooltip component:
const CustomToolTip = ({
children,
controller,
}: CustomToolTipProps) => {
const [showTip, setShowTip] = useState(false);
useEffect(() => {
if (!controller) return;
controller.addShowHandler(setShowTip);
}, []);
return (
<OverlayTrigger
onToggle={(nextShow) => {
if (!nextShow) return setShowTip(false);
controller ? controller.setShowHandlerTrue(setShowTip) : setShowTip(true);
}}
show={showTip}
overlay={(props: any) => <Overlay {...props}/>}
>
<div className={containerClassName}>{children}</div>
</OverlayTrigger>
);
};
It's not really a 'Reacty' solution but it works quite nicely. Note that the controller is completely optional here so if you wanted you could not pass that in and it would then behave like a normal popover allowing multiple tooltips at once.
Basically to use it you can create another component and instantiate a controller which you pass into CustomToolTip. Then for any tooltips which are rendered using that component, only 1 will appear at a time.
STEP 1: we declare a currentPopover variable that contain current popover id, so we are sure that there is only one popover at a time.
const [currentPopover, setCurrentPopover] = useState(null);
STEP 2: the OverlayTrigger from react-bootstrap has properties to set popover state manually. If the currentPopover variable is equal to popover id then we show the popover.
show={currentPopover === `${i}`}
STEP 3: the OverlayTrigger from react-bootstrap has properties to handle popover click manually. On click we update the currentPopover variable with the new id, except if we clicked on the current.
onToggle={() => {
if( currentPopover === `${i}` )
setCurrentPopover(null)
else
setCurrentPopover(`${i}`)
}}
RESULT:
const [currentPopover, setCurrentPopover] = useState(null);
<OverlayTrigger
trigger="click"
show={currentPopover == `${i}`}
onToggle={() => {
if( currentPopover == `${i}` )
setCurrentPopover(null)
else
setCurrentPopover(`${i}`)
}}
>
(I use ${i} as id cause my OverlayTrigger is in a loop where i is the index)