Hello - I’m trying to sort a list on the click of a button, with the below code nothing happens when I click.
If I instead have onClick={this.handleClick()} I get the error: warning: Expected onClick listener to be a function, instead got a value of object type. It seems simple, I can’t see where the problem is.
You can’t expect anything to execute after a return statement. The return value of a button click handler isn’t meaningful anyway. Furthermore, as @jenovs mentioned, your component won’t re-render unless you change the state or props of the component, so you’ll need to figure out how to set the component’s renderList to the new value (hint: check out the setState method on components)
I’m personally dreading the React course and having to use vanilla React with setState and all that, since I’ve only ever used pure functional components and redux to manage state.
I don’t think it’s a question of changing state, because it is just rearranging the array?
(it’s also within a react-redux app, so state/store is another area I’d rather avoid anyway).
If it is a redux application, you’ll want to dispatch an action, something like dispatch({type: 'SORT_LIST'}) and handle it in the reducer which should return a new state with the list sorted. If you already have a reducer defined and your component hooked up to the store with connect(), it should be pretty straightforward to do it. Otherwise it’s a little beyond the forum format to introduce react-redux at this time.
Yes it’s perfectly fine (and even recommended) for components to have local state. No need to put every piece of data into redux and write 100% functional components.
And since v16.8 introduced react hooks you can write dumb components with local state
(the props come from the store), but it still doesn’t do anything when I click. Thanks for the hooks tip, I think that might be a bit advanced, the question was to see if I know js/react fundamentals I think!
You shouldn’t be calling this.renderList() from handleClick. The way you have your render function, renderList() should take this.state.books as an argument and then if you use setState React will automatically rerender.
Also hooks are React fundamentals (since one week ago )
hmm either way it is breaking the initial receive from the store, so it renders nothing until I move around the app to trigger the fetch elsewhere, and then nothing happens on click…
I just joined discordapp dot com , a redux support group chat, they say that sort won’t work because book is an object (with string attributes) not a string! so I have to write a custom function to pass in.
I’m going to have another go!
thanks for your help
yep, I just conflated the two, cause it’s made up of string attributes. What about forceUpdate() though to prevent the need for using a component state for the re-render? …I might try that