meds
meds

Reputation: 22996

Correct way to pass arguments to reducer in React+Redux?

Seems like there's a lot of wrong ways of doing this and I'm fairly certain I'm trying to do this the wrong way (note this code doesn't work currently):

class SubmitLink extends React.Component<SubmitLinkProps, {}>{
    constructor(props: SubmitLinkProps) {
        super(props);

        this.urlToPass = "nothing";
    }

    urlToPass: string;
    handleChange(e: React.FormEvent<HTMLInputElement>) {
        this.urlToPass = e.currentTarget.value;
    }

    public render() {
        return <div>
            <div>hello world {this.props.url}</div>
            <input onChange={this.handleChange} type='text'></input>
            <button onClick={() => {
                this.props.submitlink(this.urlToPass);
            }}>submit</button>
        </div>
    }
}

Besides the fact the code doesn't work (urlToPass is undefined at runtime, unsure why) i tlooks like a tonne of work just to grab an input from a textfield. At the same time this is the only way I could find googling on how to do it but it really doesn't feel correct.

Upvotes: 0

Views: 941

Answers (2)

TheBottleSeller
TheBottleSeller

Reputation: 205

The issue here is that the element contains its own state while React components also have their own internal state. The best way to handle this is to make the React component state the source of truth. You can read more about this best practice here: https://facebook.github.io/react/docs/forms.html

In your case, it would be to do the following:

class SubmitLink extends React.Component<SubmitLinkProps, {}>{
    constructor(props: SubmitLinkProps) {
        super(props);

        this.state = { urlToPass: '' }
        this.handleChange = this.handleChange.bind(this)
    }

    handleChange(e: React.FormEvent<HTMLInputElement>) {
        this.setState({urlToPass: e.currentTarget.value});
    }

    public render() {
        return <div>
            <div>hello world {this.props.url}</div>
            <input value={this.state.urlToPass} onChange={this.handleChange} type='text'></input>
            <button onClick={() => {
                this.props.submitlink(this.state.urlToPass);
            }}>submit</button>
        </div>
    }
}

Upvotes: 2

Benjamin Hao
Benjamin Hao

Reputation: 358

You should bind the handleChange method in your constructor. this.handleChange = this.handleChange.bind(this);

Upvotes: 1

Related Questions