React/Redux Changing Webpage language - javascript

I'm making a website that have a functionality to change languages from the homescreen, I'm using Redux to handle the state.
I keep getting TypeError: Cannot read property 'connect' of undefined, and It seems to be from Home.js, I dont know why it happens!!, Please Help !!!
import React, { Component } from 'react';
import ReactRedux from 'react-redux';
import './Home.css';
import Navbar from '../../Reusable/Navbar/Navbar.js';
import Footer from '../../Reusable/Footer/Footer.js';
import Action from '../../Reusable/Action/Action.js';
import ProjectsCarousel from '../../Reusable/ProjectsCarousel/ProjectsCarousel.js';
import Getintouch from '../../Reusable/Getintouch/Getintouch.js';
import Header from './Header/Header.js';
import Info from './Info/Info.js';
import Whyus from './Whyus/Whyus.js';
import Testimonial from './Testimonial/Testimonial.js';
let actions = require('../../../actions');
class Home extends Component {
render() {
const content = this.props.content;
const switchLanguage = this.props.switchLanguage;
if (content){
return (
<div className="home">
<Action />
<Navbar data={content.page.menu} switchLanguage={switchLanguage}/>
<Header />
<Info data={content.page.home}/>
<ProjectsCarousel />
<Whyus />
<Testimonial />
<Getintouch />
<Footer />
</div>
)
} else {
return;
}
}
}
module.exports = ReactRedux.connect(
(state) => ({content: state.content}),
(dispatch) => ({switchLanguage: (lang) => dispatch(actions.switchLanguage(lang))})
)(Home);
export default Home;

That's because react-redux has only named exports.
change your import to:
import * as ReactRedux from 'react-redux';
which will import every named property to ReactRedux Object. or import it like:
import { connect } from 'react-redux';
export default connect(
(state) => ({content: state.content}),
(dispatch) => ({switchLanguage: (lang) => dispatch(actions.switchLanguage(lang))})
)(Home);

Related

How to import a react component with arrow function to app.js

Hey Developers I am new to react js. I have made a react component named todos.js with arrow fuction in
./Components/todos.js
import React from 'react'
export const todos = () => {
return (
<div>
todos works!!!
</div>
)
}
this is how my app.js look like
import './App.css';
import Header from './Components/header';
import Footer from './Components/footer';
import { Todos } from './Components/todos';
function App() {
return (
<>
<Header></Header>
<Todos></Todos>
<Footer></Footer>
</>
);
}
export default App;
import { Todos } from './Components/todos'; I am importing the todos.js file this way. But when I import that component to my app.js it throws error saying
Attempted import error: 'Todos' is not exported from './Components/todos'.
First of all component name should be Capitalised.
Second use export default const Todos
It should be an export const Todos. The component name should be Capitalised it's a batter approach as react components.
Todos.js
import React from 'react'
export const Todos = () => {
return (
<div>
Todos works!!!
</div>
)
}
App.js
import './App.css';
import Header from './Components/Header';
import Footer from './Components/Footer';
import { Todos } from './Components/Todos';
function App() {
return (
<>
<Header />
<Todos />
<Footer />
</>
);
}
export default App;

issue in redux, once create a redux application

//created action.js,rootReducer called everything in index.js but having issue on same..
//getting issue:-
Error: Could not find "store" in the context of "Connect(Home)". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(Home) in connect options.
//added rootReducer.js:-
import {combineReducers} from 'redux';
export default combineReducers({
})
//added action.js:-
export const helloRedux= () =>(dispatch:any)=>{
alert("Heloo Redux")
}
//added index.js:-
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { Provider} from 'react-redux';
import { createStore, applyMiddleware} from 'redux';
import ReduxThunk from 'redux-thunk';
import rootReducer from './rootReducer';
const store = createStore(rootReducer, applyMiddleware(ReduxThunk))
const MyAppWithStore = () => (
<Provider store={store}>
<App />
</Provider>
);
ReactDOM.render(<MyAppWithStore />, document.getElementById('root'));
serviceWorker.unregister();
//added home.js:-
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { helloRedux } from '../services/action'
class Home extends Component {
render() {
console.log(this.props)
return (
<div>
<h1>home Component</h1>
<button onClick = {() => this.props.helloRedux()}>Click Me</button>
{/* <button onClick = {() => this.helloRedux()}>Click Me</button> */}
</div>
);
}
}
const MapDispachToProps = dispach =>({
helloRedux:()=> dispach(helloRedux())
})
const mapStateToProps= state=> {
{
}
}
const HomeCom =connect(
mapStateToProps,
MapDispachToProps
)(Home)
export default HomeCom;
//app.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Home from './component/home'
function App() {
return (
<div className="App">
<header className="App-header">
{/* <img src={logo} className="App-logo" alt="logo" /> */}
<Home />
</header>
</div>
);
}
export default App;
//created action.js,rootReducer called everything in index.js but having issue on same..
//getting issue:-
Error: Could not find "store" in the context of "Connect(Home)". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(Home) in connect options.

React useEffect is not triggering on route change

I expect that console.log('Refresh') runs every time the route changes (switching from Component1 to Component2). But it's only triggering on first render. Why?
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(<BrowserRouter><App /></BrowserRouter>, document.getElementById('root'));
App.js:
import React, { useEffect } from 'react';
import { Switch, Route } from 'react-router-dom';
import Nav from './Nav';
import Component1 from './Component1';
import Component2 from './Component2';
const App = () => {
useEffect( () => console.log('Refresh'));
return (
[<Switch>
<Route component = {Nav}/>
</Switch>,
<Switch>
<Route exact path = '/component1' component = {Component1}/>
<Route exact path = '/component2' component = {Component2}/>
</Switch>]
);
}
export default App;
Nav.js:
import React from 'react';
import { Link } from 'react-router-dom';
const Nav = () => {
return (
<div>
<Link to = '/component1'>Component 1</Link>
<Link to = '/component2'>Component 2</Link>
</div>
);
}
export default Nav;
Component1.js:
import React from 'react';
const Component1 = () => {
return (
<div>
<p>Hi</p>
</div>
);
}
export default Component1;
Component2.js:
import React from 'react';
const Component2 = () => {
return (
<div>
<p>Bye</p>
</div>
);
}
export default Component2;
The useEffect is not triggered because the App component is not re-rendered, nothing changed in that component (no state or props update).
If you want the App component to re-render when the route change, you can use the withRouter HOC to inject route props, like this :
import { Switch, Route, withRouter } from 'react-router-dom';
const App = () => {
useEffect( () => console.log('Refresh'));
return (...);
}
export default withRouter(App);
Example : https://codesandbox.io/s/youthful-pare-n8p1y
use the key attribute so everytime we render new component (different key)
<Route path='/mypath/:username' exact render= {routeProps =><MyCompo {...routeProps} key={document.location.href} />} />
Use the 2nd argument to useEffect to conditionally apply effect. For example via react-router-dom, you get some properties
const { schoolId, classId } = props
useEffect(() => {
// fetch something here
}, [schoolId, classId)
Here [schoolId, classId acts as the unique identifier for useEffect to trigger.
Using Hooks:
use useLocation and useLayoutEffect get more efficiency:
import { useLocation } from "react-router-dom";
//...
const location = useLocation();
//...
useLayoutEffect(() => {
console.log("location",location)
}, [location])

React-Router v4.2.2 not working (I think I've done something wrong in the Route tag?)

I'm using react-router v4.2.2 in my project, and am trying to create a set of cards that each link to other components. Right now I'm just testing that the router works, by routing each Card to one specific component called 'Project1'. This, however, is not working; I'm not seeing the div inside the Project1 component pop up. What am I doing wrong?? Shouldn't each Card link to the Project1 component?
Here is the code for the main container that holds the cards:
import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import ProjectCard from '../components/project_card.js';
import Project1 from '../components/project1.js';
class ProjectCards extends React.Component {
render() {
var projectCards = this.props.projects.map((project, i) => {
return (
<div key={i}>
<Link to={`/${project.title}`}>
<ProjectCard title={project.title} date={project.date} focus={project.focus}/>
</Link>
</div>
);
});
return (
<div>{projectCards}</div>
);
}
}
function mapStateToProps(state) {
return {
projects: state.projects
};
}
export default connect(mapStateToProps)(ProjectCards);
Here is the code for the Routes container:
import React from 'react';
import Project1 from '../components/project1.js';
import { connect } from 'react-redux';
import { Route, Switch } from 'react-router-dom';
class Routes extends React.Component{
render() {
var createRoutes = this.props.projects.map((project, i) => {
return <Route key={i} exact path={`/${project.title}`} component={Project1}/>
});
return (
<Switch>
{createRoutes}
</Switch>
);
}
}
function mapStateToProps(state) {
return {
projects: state.projects
};
}
export default connect(mapStateToProps)(Routes);
Here is the code for the index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyMiddleware, createStore } from 'redux';
import ReduxPromise from 'redux-promise';
import { BrowserRouter } from 'react-router-dom';
import App from './components/App.jsx';
import css from '../style/style.css';
import style from '../style/style.css';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
, document.getElementById('root'));
and the code for Project1, which should display when a Card has been clicked:
import React from 'react';
const Project1 = () => {
return (
<div>hello there this is Project1</div>
);
}
export default Project1;
When you click on a link, you navigate to Project1, which has no Routes defined. You basically destroy your Route when you lick on it because the Switch is in the same component as the Link. The Switch statement needs to be moved to a 3rd component so that it still exists after clicking on a linking card.

Why Material-UI Appbar onLeftIconButtonTouchTap is not work?

Im studying React-Redux, Material-UI.
Now, Im trying to create Sample App, but not work.
I dont know how to improve my code.
I want to open Drawer , when Material-UI AppBar onLeftIconButtonTouchTap is clicked.
I cant bind my Action to Component, I think.
When following code is running, not fire onLeftIconButtonTouchTap event.
And when I change openDrawer to openDrawer(), JS error 'openDrawer is not a function' is found on Chrome Dev tool.
Header.jsx as a Component
import React, { PropTypes } from 'react';
import AppBar from 'material-ui/AppBar';
import Drawer from 'material-ui/Drawer';
const Header = ({
openDrawer,
open
}) => (
<div>
<AppBar
title='sample'
onLeftIconButtonTouchTap = {() => openDrawer}
/>
<Drawer
docked={false}
open={open}
/>
</div>
)
Header.PropTypes = {
openDrawer: PropTypes.func.isRequired,
open: PropTypes.bool.isRequired
}
export default Header;
HeaderContainer.jsx as a Container
import React from 'react';
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux';
import { header } from '../actions'
import Header from '../components/Header';
const mapStateToProps = (state) => ({open});
const mapDispatchToProps = (dispatch) => (
{openDrawer: bindActionCreators(header, dispatch)}
);
const HeaderContainer = connect(
mapStateToProps,
mapDispatchToProps
)(Header);
export default HeaderContainer;
App.jsx as a RootComponent
import React, { Component, PropTypes } from 'react';
import Header from '../components/Header';
import injectTapEventPlugin from "react-tap-event-plugin";
import baseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
injectTapEventPlugin();
class App extends Component {
constructor(props) {
super(props);
}
getChildContext() {
return { muiTheme: getMuiTheme(baseTheme) };
}
render() {
return (
<div>
<Header />
{this.props.children}
</div>
);
}
};
App.childContextTypes = {
muiTheme: React.PropTypes.object.isRequired,
};
export default App;
Thanks in advance.
You are not binding the function correctly. You need to update your code to
<AppBar
title='sample'
onLeftIconButtonTouchTap = { openDrawer.bind(this) }
/>
More about .bind() method here: Use of the JavaScript 'bind' method

Categories