react-navigation icon indicating copy to clipboard operation
react-navigation copied to clipboard

Best pattern for a 'Save' button in the header

Open despreston opened this issue 9 years ago • 113 comments

Often times if you are editing or creating something, one of the header buttons will be 'Save'. I don't see how this is feasible with this library since there is no access to the state or props of the current screen component. The only (ugly) solution would be to keep the data to be saved outside of the component. Anyone have any suggestions how this pattern can be achieved with this library?

despreston avatar Feb 01 '17 23:02 despreston

On a somewhat related note, Ive seen references to a Slack channel. That would be a better place for this discussion but I'm unsure of how to get access to that channel.

despreston avatar Feb 01 '17 23:02 despreston

There is some discussion on the reactiflux discord server (https://www.reactiflux.com/), specifically in the rn-navigation channel, although I don't think its specifically for this library.

dmhood avatar Feb 01 '17 23:02 dmhood

Related: #149

chuckhacker avatar Feb 02 '17 03:02 chuckhacker

the only solution I can think of is using setParams to set the callback/state in the controller and using state.params in the header

Schniz avatar Feb 02 '17 17:02 Schniz

Thanks @Schniz . Thats the pattern I was thinking as well and the path that I ultimately took. Unfortunately I ran into what appears to be a bug related to calling setParams. Ive opened a separate issue for that bug. All in all, this pattern seems a bit hazy and not entirely 'safe' unless you explicitly check for the existence of all state.params.

despreston avatar Feb 02 '17 17:02 despreston

Yeah. I think that state.params should default to an empty object.

Schniz avatar Feb 02 '17 17:02 Schniz

However, I really dig using ramda's pathOr for these kind of problems.

import { pathOr } from 'ramda';
const noop = () => {};
// ...
const somethingToDoFn = pathOr(noop, ['params', 'somethingToDoFn'], navigator);
somethingToDoFn('data', 'to', 'pass');

Schniz avatar Feb 02 '17 17:02 Schniz

Isn't the proper way to do this:

componentDidMount () {
    const isDisabled = <someLogicUsingLocalState>;
    const params = {
            right: (
                <Button
                    onPress={() =>!isDisabled ? this.onSave() : null}
                >
                    <Text style={[styles.rightButtonTextStyle, isDisabled ? styles.disabledStyle : null]}>
                        Save
                    </Text>
                </Button>
            ),
        };
    this.props.navigation.setParams(params);
 }

However, https://github.com/react-community/react-navigation/issues/160 is preventing this from working well.

dmhood avatar Feb 02 '17 19:02 dmhood

Thought I would post my main navigation options too for completness sake:

function getCurrentParams (state) {
    if (state.routes) {
        return getCurrentParams(state.routes[state.index]);
    }
    return state.params || {};
}

...some setup...

// main stack navigator navigationOptions
navigationOptions: {
    header: ({state}) => {
        // get the "deepest" current params.
        const currentParams = getCurrentParams(state);

        const left = currentParams.left;
        const right = currentParams.right;
        const style = currentParams.style;
        const tintColor = currentParams.tintColor;
        return { left, right, style, tintColor };
    }
 }

This feels kinda hacky to me, but I don't see another way to set dynamic header properties other than the use of setParams (and again, https://github.com/react-community/react-navigation/issues/160 makes this a poor solution at the moment).

dmhood avatar Feb 04 '17 01:02 dmhood

Given that #160 is already fixed, do you think @dmhood your solution can become more standardised? Do you think it deserves a doc How to just for the sake of avoiding these questions in the future?

grabbou avatar Feb 09 '17 08:02 grabbou

If people find that useful then I'll make a pr here in the next couple of days, and we can standardize/critique it there.

dmhood avatar Feb 10 '17 07:02 dmhood

@dmhood solution works great. I was looking to show a modal view when pressing one of the header buttons (left or right). Thanks!

prodz18 avatar Feb 12 '17 02:02 prodz18

FWIW using setParams in componentDidMount is apparently discouraged, (see #296). I've mostly gone to pulling most of the "initial state" logic to set header buttons out into static/helper functions, which isn't great but should be doable unless your component uses something external like react-context.

dmhood avatar Feb 14 '17 19:02 dmhood

I'm not sure I understood @dmhood's solution. How do I call the saveDetails() function? This code throws error, by the way: "_this2.saveDetails is not a function". Help would be appreciated. Thanks!

class MyScreen extends React.Component {
    static navigationOptions = {
        header: {
            right: <Button title={"Save"} onPress={() => this.saveDetails()} />
        }
    };

    saveDetails() {
        alert('Save Details');
    }

    render() {
        return (
            <View />
        );
    }
}

raymundtusk7 avatar Feb 18 '17 10:02 raymundtusk7

@raymundtusk7 you can't call this.saveDetails() from a static context since the actual saveDetails method is a class method. You would need to make saveDetails static or just some helper function outside of the class.

dmhood avatar Feb 21 '17 01:02 dmhood

Maybe all the functions (when declaring navigationOptions as a function for instance) should receive the actual component as an argument

Schniz avatar Feb 21 '17 08:02 Schniz

Can't seem to wrap my head around this. If I make the saveDetails static, would it have access to the screen's state object?

Another scenario: Let's say I have a login screen with 2 text inputs and a login button at the header's right component. How would it send the details to the REST API via fetch?

raymundtusk7 avatar Feb 21 '17 09:02 raymundtusk7

Try setting your component instance's handleSave function as a navigation state parameter, after the component has mounted. Something like:

class MyScreen extends React.Component {
    static navigationOptions = {
        header: ({ state }) => ({
            right: <Button title={"Save"} onPress={state.params.handleSave} />
        })
    };

    saveDetails() {
        alert('Save Details');
    }

    componentDidMount() {
      this.props.navigation.setParams({ handleSave: this.saveDetails });
    }

    render() {
        return (
            <View />
        );
    }
}

stevehollaar avatar Feb 21 '17 17:02 stevehollaar

@stevehollaar: Awesome! This worked for me though:

<Button title={"Save"} onPress={() => {state.params.handleSave()}} />

But you pointed me to the right direction. Thanks a lot! 💯

raymundtusk7 avatar Feb 22 '17 12:02 raymundtusk7

Is there a way to dynamically enable or disable it? Meaning, if the user changes input the Save button would be enabled

arstiefel avatar Feb 22 '17 18:02 arstiefel