Routing with Link is not working with const component react redux - reactjs

I want a link in the but then i dont know how to i use it with const
with class it works. can anyone please explain about const components
import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
const mapStateToProps= state =>{
return { articles :state.articles};
}
const connectedList = ({ articles }) =>(
articles.map(e=>(
<li key={e.id}>{e.title}</li>
))
<Link to="/Form">Form</Link>//// this line is error thrown
);
const List= connect(mapStateToProps)(connectedList);
export default List;
I know I'm do it the wrong way as i have no idea how do i achieve it the right way

You have some syntax errors. Most importantly, your "connectedList" didn't actually return/render anything.
You would have run into other problems because you hadn't wrapped your array of <li>s into a <ul>, but also, a React component render expects there to be only a single element at the top-level -- which is why I wrapped everything in a <div>.
I've cleaned up some items for clarity and used a React class instead of a functional component:
import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
class List extends React.Component {
render() {
const { articles } = this.props
const articleListItems = articles.map(article => {
return <li key={article.id}>{article.title}</li>
})
return (
<div>
<ul>
{articleListItems}
</ul>
<Link to="/Form">Form</Link>
</div>
)
}
}
const mapStateToProps = state => {
return {
articles: state.articles
}
}
const ListContainer = connect(mapStateToProps, null)(List)
export default ListContainer

Related

How to use refs in react through react-redux , withRouter?

I'm trying to use ref in a component connected to react-redux
I've tried this solution.
connect(null, null, null, {forwardRef: true})(myCom)
<myCom ref={ref => this.myCom = ref} />
this works just fine according to react-redux docs, but now when i try using
withRouter at the same time i get an error:
Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
so the final export code i have tried which lead to the above error
export default connect(null, null, null, { forwardRef: true })(withRouter(withStyles(styles)(myCom)));
Note: withStyles doesn't cause any issues as i've tried removing only withRouter, the issue was resolved.
is there any solution to solve this issue ?
In order to pass a ref to a component wrapped by withRouter you need to call it wrappedComponentRef. I recommend having withRouter as the outermost wrapper, so your example would look like the following:
withRouter(connect(null, null, null, {forwardRef: true})(myCom));
<myCom wrappedComponentRef={ref => this.myCom = ref} />
The following example and description are adapted from a related answer of mine: Get ref from connected redux component withStyles
Below is code from a modified version of the react-redux todo list tutorial that shows the correct syntax. I've included here the two files that I changed (TodoList.js and TodoApp.js), but the sandbox is a fully working example.
In TodoApp, I use the ref (via the wrappedComponentRef property) on TodoList to get and display its height. The displayed height will only get updated if TodoApp re-renders, so I've included a button to trigger a re-render. If you add a couple todos to the todo list, and then click the re-render button, you will see that the new height of the list is displayed (showing that the ref is fully working).
In TodoList, I'm using withStyles to add a blue border around the todo list to show that withStyles is working, and I'm displaying the primary color from the theme to show that withTheme is working. I am also displaying the location object from withRouter to demonstrate that withRouter is working.
TodoList.js
import React from "react";
import { connect } from "react-redux";
import Todo from "./Todo";
import { getTodosByVisibilityFilter } from "../redux/selectors";
import { withStyles, withTheme } from "#material-ui/core/styles";
import clsx from "clsx";
import { withRouter } from "react-router-dom";
const styles = {
list: {
border: "1px solid blue"
}
};
const TodoList = React.forwardRef(
({ todos, theme, classes, location }, ref) => (
<>
<div>Location (from withRouter): {JSON.stringify(location)}</div>
<div>theme.palette.primary.main: {theme.palette.primary.main}</div>
<ul ref={ref} className={clsx("todo-list", classes.list)}>
{todos && todos.length
? todos.map((todo, index) => {
return <Todo key={`todo-${todo.id}`} todo={todo} />;
})
: "No todos, yay!"}
</ul>
</>
)
);
const mapStateToProps = state => {
const { visibilityFilter } = state;
const todos = getTodosByVisibilityFilter(state, visibilityFilter);
return { todos };
};
export default withRouter(
connect(
mapStateToProps,
null,
null,
{ forwardRef: true }
)(withTheme(withStyles(styles)(TodoList)))
);
TodoApp.js
import React from "react";
import AddTodo from "./components/AddTodo";
import TodoList from "./components/TodoList";
import VisibilityFilters from "./components/VisibilityFilters";
import "./styles.css";
export default function TodoApp() {
const [renderIndex, incrementRenderIndex] = React.useReducer(
prevRenderIndex => prevRenderIndex + 1,
0
);
const todoListRef = React.useRef();
const heightDisplayRef = React.useRef();
React.useEffect(() => {
if (todoListRef.current && heightDisplayRef.current) {
heightDisplayRef.current.innerHTML = ` (height: ${
todoListRef.current.offsetHeight
})`;
}
});
return (
<div className="todo-app">
<h1>
Todo List
<span ref={heightDisplayRef} />
</h1>
<AddTodo />
<TodoList wrappedComponentRef={todoListRef} />
<VisibilityFilters />
<button onClick={incrementRenderIndex}>
Trigger re-render of TodoApp
</button>
<div>Render Index: {renderIndex}</div>
</div>
);
}
Use compose method and try something like this
const enhance = compose(
withStyles(styles),
withRouter,
connect(mapStateToProps, null, null, { forwardRef: true })
)
and use it before exporting component
export default enhance(MyComponent)
You can do it this way! This will work for sure👍
import { withRouter } from 'react-router';
//Just copy and add this withRouterAndRef HOC
const withRouterAndRef = (WrappedComponent) => {
class InnerComponentWithRef extends React.Component {
render() {
const { forwardRef, ...rest } = this.props;
return <WrappedComponent {...rest} ref={forwardRef} />;
}
}
const ComponentWithRouter = withRouter(InnerComponentWithRef, { withRef: true });
return React.forwardRef((props, ref) => {
return <ComponentWithRouter {...props} forwardRef={ref} />;
});
}
class MyComponent extends Component {
constructor(props) {
super(props);
}
}
//export using withRouterAndRef
export default withRouterAndRef (MyComponent)

How to use map on multi objects array in React

This is child component as i can you Props here
Child Component:
import React from "react";
const PeopleList = props => {
console.log("child Props :", props.data);
const list = props.data.map(item => item.name);
return <React.Fragment>{"list"}</React.Fragment>;
};
export default PeopleList;
Main Component:
import React, { Component } from "react";
import { connect } from "react-redux";
import { fetchPeople } from "../actions/peopleaction";
import PeopleName from "../containers/peopleName";
class Main extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
this.props.dispatch(fetchPeople());
}
render() {
const { Error, peoples } = this.props;
console.log("data", peoples);
return (
<div className="main">
{"helo"}
<PeopleName data={peoples.results} />
</div>
);
}
}
const mapStateToProps = state => {
return {
peoples: state.peoples.peoples,
error: state.peoples.error
};
};
export default connect(mapStateToProps)(Main);
If i iterate the props multi objects array i can face Map is not define issue;
I need to iterate the props.data multi objects array in child component and i get object from Redux store. once component loaded the redux store.
can you please some one help me on this.
you can find whole code below mentioned
Try this It works in your codesandbox.
{peoples.results && <PeopleName data={peoples.results} />}

Attempted import error: does not contain a default export

I'm defining react component to connect with redux . I have the app and list components
App.js
import React, { Component } from 'react';
//import Login from './components/Login';
import List from './components/List';
import './App.css';
class App extends Component {
render() {
return ( <List />); } }
export default App;
List.js
import React from 'react';
import { connect } from 'react-redux';
const mapStateToProps= state =>{
return { articles :state.articles};
}
const connectedList = ({ articles }) =>(
{articles.map(e=>( //////**1) here I get red under the dot(.) ie., error**
<li key={e.id}>{e.title}</li>
))}
);
const List= connect(mapStateToProps)(connectedList);
export default List;
why do 1) here I get red under the dot(.) ie., error
I have exported List but I'm thrown this error
Attempted import error: './components/List' does not contain a default export (imported as 'List').
Actually I'm newbie to redux so Please explain lemme know where i'm going wrong?
Remove curly brace:
const connectedList = ({ articles }) =>(
articles.map(e=>( // implicit return
<li key={e.id}>{e.title}</li>
)
));
Or, using curly brace:
const connectedList = ({ articles }) => { // no parentheses
return articles.map(e=>( // explicitly use return
<li key={e.id}>{e.title}</li>
)
});
Using curly brace in parentheses indicates that you're returning an object. But articles.map... is obviously not an object rather looping through an object.

react-async-poll with a connected component

Looking at the docs for react-async-poll I'm following the Usage example to integrate asyncPoll into my component, but I'm getting a Uncaught TypeError: dispatch is not a function complaint from within my onPollinterval function
import React, { Component } from 'react';
import { connect } from 'react-redux';
import asyncPoll from 'react-async-poll';
import { fetchCaCities, } from '../actions';
import MyMap from './my-map';
class CaliforniaMap extends Component {
componentDidMount() {
this.props.fetchCaCities();
}
render() {
return (
<div>
<h1>California Map</h1>
<MyMap center={[37.5, -120]} zoom={6} layers={[this.props.caCities]} />
</div>
);
}
}
const onPollInterval = (props, dispatch) => {
console.log(dispatch); // undefined
return dispatch(fetchCaCities());
};
const mapStateToProps = state => ({
caCities: state.map.california.caCities,
});
export default asyncPoll(60 * 1000, onPollInterval)(connect(
mapStateToProps, { fetchCaCities }
)(CaliforniaMap)
Maybe react-async-poll doesn't work for connected components?
According to the docs:
The dispatch parameter is only passed to [onInterval] if it is
available in props, otherwise it will be undefined.
The example they give is confusing because it does not define dispatch anywhere, but they show onPollInterval using it.

Which way should I use for Connector in Redux?

I seen 2 ways of doing the same thing but I am not sure what is the proper way.
Component
import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {selectUser} from '../actions/index'
class UserList extends Component {
renderList() {
return this.props.users.map((user) => {
return (
<li
key={user.id}
onClick={() => this.props.selectUser(user)}
>
{user.first} {user.last}
</li>
);
});
}
render() {
return (
<ul>
{this.renderList()}
</ul>
);
}
}
// Get apps state and pass it as props to UserList
// > whenever state changes, the UserList will automatically re-render
function mapStateToProps(state) {
return {
users: state.users
};
}
// Get actions and pass them as props to to UserList
// > now UserList has this.props.selectUser
function matchDispatchToProps(dispatch){
return bindActionCreators({selectUser: selectUser}, dispatch);
}
// We don't want to return the plain UserList (component) anymore, we want to return the smart Container
// > UserList is now aware of state and actions
export default connect(mapStateToProps, matchDispatchToProps)(UserList);
https://github.com/buckyroberts/React-Redux-Boilerplate
Or
import React from "react"
import { connect } from "react-redux"
import { fetchUser } from "../actions/userActions"
import { fetchTweets } from "../actions/tweetsActions"
#connect((store) => {
return {
user: store.user.user,
userFetched: store.user.fetched,
tweets: store.tweets.tweets,
};
})
export default class Layout extends React.Component {
componentWillMount() {
this.props.dispatch(fetchUser())
}
fetchTweets() {
this.props.dispatch(fetchTweets())
}
render() {
const { user, tweets } = this.props;
if (!tweets.length) {
return <button onClick={this.fetchTweets.bind(this)}>load tweets</button>
}
const mappedTweets = tweets.map(tweet => <li>{tweet.text}</li>)
return <div>
<h1>{user.name}</h1>
<ul>{mappedTweets}</ul>
</div>
}
}
https://github.com/learncodeacademy/react-js-tutorials/tree/master/5-redux-react
The first way uses 2 different functions mapStateToProps() and matchDispatchToProps() while the other way uses #connect(....).
When I use the #connect I get a whole bunch of warnings saying that it has not been finalized and might change.
The # symbol is a decorator which is still considered experimental. So I would use that at your own risk. Your first code block is the safer way to do it as described in the official docs. Both blocks essentially do the same thing but decorators are more sugar than anything.
References:
https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options
What's the '#' (at symbol) in the Redux #connect decorator?
I think the first method will give you less problems in the end. Someone else can chime in though too.
The answer by Jackson is right in every sense however he is missing out the importance of using the first version for the usage of unit testing. If you want to be able to unit test a component (which usually means testing with the unconnected version) you need to be able to export the connected and unconnected component.
Using your example and assuming you are using jest/enzyme you could do something like this:
// notice importing the disconnected component
import { UserList } from '../relative/file/path/UserList'
import { mount } from 'enzyme'
describe('UserList', () => {
it('displays the Username', () => {
const users = [{fist: 'Person', last: 'Thing'}, ... ]
const UserList = mount(<UserList users={users} />)
export(UserList.find('li')[0].text()).toEqual('Person Thing')
});
});
Once you build larger projects being able to unit test will provide sanity to your coding life. Hope this helps

Resources