axios.post doesn't seem to work? - node.js

Maybe I am just not using axios correctly but I currently have a react front-end and node.js back end.
I am trying to POST to my api endpoint "/api/:id/addItem" but nothing is logging when making the request.
Here is my code:
ListForm component ->
import React from 'react';
import * as helpers from '../helpers';
class ListForm extends React.Component {
state = {
value: ''
}
handSubmit = e => {
e.preventDefault();
helpers.addItem(this.props.currentUser.googleId, this.state.value);
this.setState({value: ''});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text"
value={this.state.value}
onChange={e => this.setState({value: e.target.value})}
/>
<button>Add item</button>
</form>
);
}
}
export default ListForm;
Routes ->
const mongoose = require('mongoose');
const User = require('../models/userSchema');
module.exports = (app) => {
app.post('/api/:id/addItem', (req, res) => {
console.log('HEY!');
});
};
helpers.js ->
import axios from 'axios';
export const fetchUser = async () => {
const resp = await axios.get('/api/current_user');
return resp.data;
}
export const addItem = async (id, newItem) => {
const resp = await axios.post("/api/" + id + "/addItem", newItem);
return resp.data;
}
Package.json to show forwarding requests->
{
"name": "client",
"version": "0.1.0",
"private": true,
"proxy": {
"/auth/google": {
"target": "http://localhost:5000"
},
"/api/*": {
"target": "http://localhost:5000"
}
},
"dependencies": {
"axios": "^0.17.1",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-scripts": "1.0.17"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}

Issue here is with newItem , its not json it's just simple value
axios.post("/api/" + id + "/addItem", newItem);
It should be like :
axios.post("/api/" + id + "/addItem", {value : newItem});
Or pass json from addItem :
helpers.addItem(this.props.currentUser.googleId, this_should_be_json );

Related

MangoDB Compass can not connect to my backend using TypeORM

I am trying to create a simple web application where I can diplay users from a MongoDB database on a React web application.
However I am stuck on a problem with TypeORM and my MongoDB database. Indeed, my backend repository can not access to the database.
Here is my package.json file :
{
"name": "backend",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"build": "tsc",
"dev": "nodemon index.ts",
"start": "node ./dist/index.js",
"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/.bin/typeorm",
"migration:generate": "npm run typeorm -- migration:generate --config src/config/ormconfig.json --connection --name ",
"migration:run": "npm run typeorm -- migration:run"
},
"license": "UNLICENSED",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"mongodb": "^3.6.0",
"typeorm": "^0.3.11"
},
"devDependencies": {
"#types/cors": "^2.8.13",
"#types/express": "^4.17.14",
"#types/mongodb": "^4.0.7",
"#types/node": "^18.11.8",
"nodemon": "^2.0.20",
"ts-node": "^10.9.1",
"typescript": "^4.8.4"
}
}
Here is my connectionService.ts file, which is supposed to create the connection to the database :
import { DataSource, DataSourceOptions } from "typeorm"
import { Utilisateurs } from "../entities/utilisateurs";
class connectionServices{
public myDataSource:DataSource;
constructor(dbConfig: DataSourceOptions){
this.myDataSource = new DataSource(dbConfig)
}
public async getUsers (){
const myusers = this.myDataSource.getMongoRepository(Utilisateurs);
const data = await myusers.find({});
console.log (data);
return data;
}
}
export default (connectionServices);
Here is my index.ts file :
import express from 'express';
import cors from 'cors';
import connectionServices from "./service/connectionService";
function main() {
const app = express();
const service = new connectionServices({
type: "mongodb",
url: "mongodb://localhost:27017",
port: 27017,
database: "users",
synchronize: true,
entities: [
"src/entities/**/*.ts"
],
});
app.use(cors())
app.get('/users/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
app.get('/', (req, res) => {
res.send('Well done!');
})
app.listen(4321, () => {
console.log('The application is listening on port 4321!');
})
app.get('/users', (req,res) => {
res.send(service.getUsers());
})
}
main();
And finally here is my ormconfig.json file :
{
"type": "mongodb",
"host": "localhost",
"url": "mongodb://localhost:27017",
"port": 27017,
"database": "test",
"synchronize": true,
"logging": false,
"entities": [
"src/entity/**/*.ts"
],
"migrations": [ "src/migration/**/*.ts"
],
"subscribers": [ "src/subscriber/**/*.ts"
],
"cli": {
"entitiesDir": "src/entity", "migrationsDir": "src/migration", "subscribersDir": "src/subscriber"
}
}
The backend builds and launches properly :
However when I type in the url http://localhost:4321/users, I get this error in my terminal and the backend crashes :
I have tried to put the url of the data base, or put the parameter "host": "localhost" with the correct port but nothing worked.
I have looked on several tutorials, videos without success...
If someone sees the solution to my problem that would be great!
You didn't provide your entities. however, I think the problem occurred because typeorm couldn't find your entities.
try changing src/entity/**/*.ts to src/entity/**/*{.ts,.js}.
Do the same thing for migration and subscribers if needed.
In fact the problem was in the index.ts file and in the connectionService.ts file.
In the service, it was missing a function in order to connect to the data base :
import { createConnection, DataSource, DataSourceOptions } from "typeorm"
import { Utilisateurs } from "../entities/utilisateurs.entity";
class connectionServices{
public myDataSource:DataSource;
async connect(){
await this.myDataSource.connect();
}
constructor(dbConfig: DataSourceOptions){
this.myDataSource = new DataSource(dbConfig);
}
public async getUsers (){
const myusers = this.myDataSource.getMongoRepository(Utilisateurs);
const data = await myusers.find({});
console.log (data);
return data;
}
}
export default (connectionServices);
And in the index.ts file, I was calling the promise of a table containing the date, and not the data. Here is the working file :
import express from 'express';
import cors from 'cors';
import connectionServices from "./service/connectionService";
import { Utilisateurs } from './entities/utilisateurs.entity';
async function main() {
const app = express();
const service = new connectionServices({
type: "mongodb",
host: "localhost",
port: 27017,
database: "users",
synchronize: true,
entities: [
Utilisateurs
],
});
await service.connect();
app.use(cors())
app.get('/users/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
app.get('/', (req, res) => {
res.send('Well done!');
})
app.listen(4321, () => {
console.log('The application is listening on port 4321!');
})
app.get('/users', async(req,res) => {
res.send(await service.getUsers());
})
}
main();
With these modifications, everything works properly.

`useTheme` must be used within `NativeBaseConfigProvider`

In my project I faced the above error can anyone tell me how to solve this error.
The error I faced is:
Error: useTheme must be used within NativeBaseConfigProvider
This error is located at:
in Container
in ProductContainer (created by App)
in RCTView (created by View)
in View (created by App)
in App (created by ExpoRoot)
in ExpoRoot
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
ProductContainer.js:
import React, { useState, useEffect } from 'react'
import { View, StyleSheet, ActivityIndicator, FlatList, Text} from 'react-native'
import { Container, Header, Icon, Item, Input } from 'native-base';
import ProductList from './ProductList';
import SearchedProduct from './SearchedProducts';
const data = require('../../assets/data/products.json');
const ProductContainer = () => {
const [products, setProducts ] = useState([]);
const [productsFiltered, setProductsFiltered] = useState([]);
const [focus, setFocus] = useState();
useEffect(() => {
setProducts(data);
setProductsFiltered(data);
setFocus(false);
return () => {
setProducts([])
setProductsFiltered([])
setFocus()
}
}, [])
const SearchProduct = (text) => {
setProductsFiltered(
products.filter((i) => i.name.toLowerCase().includes(text.toLowerCase()))
);
}
const openList = () => {
setFocus(true);
}
const onBlur = () => {
setFocus(flase);
}
return (
<Container>
<View style = {{ flexDirection: "row"}}>
<Input
width = "100%"
variant = "rounded"
placeholder="Search"
onFocus={openList}
onChangeText={(text) => SearchProduct(text)}
/>
</View>
{focus == true ? (
<SearchProduct
productsFiltered={productsFiltered}
/>
) : (
<View style={styles.container}>
<Text>Product Container</Text>
<View style={styles.listContainer}>
<FlatList
data={products}
numColumns={2}
renderItem={({item}) => <ProductList
key={item.brand}
item={item}/>}
keyExtractor={item => item.brand}
/>
</View>
</View>
)}
</Container>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
export default ProductContainer
App.js
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
//Screens
import Header from './Shared/Header'
import ProductContainer from './Screens/Products/ProductContainer'
export default function App() {
return (
<View style={styles.container}>
<Header />
<ProductContainer />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
package.json:
{
"name": "animal-feedmart",
"version": "1.0.0",
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"eject": "expo eject"
},
"dependencies": {
"expo": "~44.0.0",
"expo-status-bar": "~1.2.0",
"native-base": "^3.3.7",
"react": "17.0.1",
"react-dom": "17.0.1",
"react-native": "0.64.3",
"react-native-base": "^1.1.0",
"react-native-safe-area-context": "^4.2.1",
"react-native-svg": "^12.3.0",
"react-native-web": "0.17.1"
},
"devDependencies": {
"#babel/core": "^7.12.9"
},
"private": true
}
Please can anyone help me solve this issue? Thanks in advance
in your app.js import NativeBaseProvider and wrap your other components with it
import { NativeBaseProvider } from 'native-base';
return (
<NativeBaseProvider>
{Your other components}
</NativeBaseProvider>
);
If you put in the native provider and it is still showing the error, please ensure to change your Header as native base removed it from v3 upward, use HStack instead and if you want to use the Header downgrade the native base version to v2.12.14
import { NativeBaseProvider } from 'native-base';
export default function App() {
return (
<NativeBaseProvider>
<View style={styles.container}>
<Header />
<ProductContainer />
<StatusBar style="auto" />
</View>
</NativeBaseProvider>
);
}
I have solved this in App.js
import { NavigationContainer } from '#react-navigation/native';
import { NativeBaseProvider, extendTheme } from 'native-base';
Create a Theme
const newColorTheme = {
brand: {
900: '#5B8DF6',
800: '#ffffff',
700: '#cccccc',
},
};
const theme = extendTheme({
colors: newColorTheme,
});
and use on
export default function App() {
return (
<NativeBaseProvider theme={theme}>
<NavigationContainer>
<Header />
<Main/>
</NavigationContainer>
</NativeBaseProvider>
);
}

PrivateRoute not redirecting in reactjs

I was building a website for developers following a Udemy course. It redirects users to the dashboard after they log in. I need to make the dashboard page private, so that only logged-in users can access it, therefore I put it in a private route. If a user signs out, I need to redirect the user to the sign in page using the privateroute function, however private route does not redirect it will stay on dashboard page, and when I type localhost://3000/dashboard I can access dashboard page without the user having to log in
I need your help to fix this
Thankyou in advance
dashboard components
import React from 'react';
import PropTypes from 'prop-types';
const Dashboard = props => {
return <div>Dashboard</div>;
};
Dashboard.propTypes = {};
export default Dashboard;
PrivateRoute components
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
const PrivateRoute = ({
component: Component,
auth: { isAuthenticated, loading },
...rest
}) => (
<Route
{...rest}
render={props =>
!isAuthenticated && !loading ? (
<Redirect to='/login' />
) : (
<Component {...props} />
)
}
/>
);
PrivateRoute.propTypes = {
auth: PropTypes.object.isRequired,
};
const mapStateToProps = state => ({
auth: state.auth,
});
export default connect(mapStateToProps)(PrivateRoute);
App.js
import React, { Fragment, useEffect } from 'react';
import './App.css';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Navbar from './components/layout/Navbar';
import Landing from './components/layout/Landing';
import Login from './components/auth/Login';
import Register from './components/auth/Register';
import Alert from './components/layout/Alert';
// Redux
import { Provider } from 'react-redux';
import store from './store';
import { loadUser } from './actions/auth';
import setAuthToken from './utils/setAuthToken';
import Dashboard from './components/dashboard/Dashboard';
import PrivateRoute from './components/routing/PrivateRoute';
if (localStorage.token) {
setAuthToken(localStorage.token);
}
const App = () => {
useEffect(() => {
store.dispatch(loadUser());
}, []);
return (
<Provider store={store}>
<Router>
<Fragment>
<Navbar />
<Route exact path='/' component={Landing} />
<section className='container'>
<Alert />
<Switch>
<Route exact path='/register' component={Register} />
<Route exact path='/login' component={Login} />
<PrivateRoute exact path='/dashboard' component={Dashboard} />
</Switch>
</section>
</Fragment>
</Router>
</Provider>
);
};
export default App;
**auth.js **
import {
REGISTER_SUCCESS,
REGISTER_FAIL,
USER_LOADED,
AUTH_ERROR,
LOGIN_FAIL,
LOGIN_SUCCESS,
LOGOUT,
} from '../actions/types';
const initialState = {
token: localStorage.getItem('token'),
isAuthenticated: null,
loading: true,
user: null,
};
export default function (state = initialState, action) {
const { type, payload } = action;
switch (type) {
case USER_LOADED:
return {
...state,
isAuthenticated: true,
loading: false,
user: payload,
};
case REGISTER_SUCCESS:
case LOGIN_SUCCESS:
localStorage.setItem('token', payload.token);
return {
...state,
...payload,
isAuthenticated: true,
loading: false,
};
case REGISTER_FAIL:
case AUTH_ERROR:
case LOGIN_FAIL:
case LOGOUT:
localStorage.removeItem('token');
return {
...state,
token: null,
isAuthenticated: false,
loading: false,
};
default:
return state;
}
}
package.json in client side
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.1",
"#testing-library/react": "^12.1.2",
"#testing-library/user-event": "^13.5.0",
"axios": "^0.24.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^6.0.0",
"react-router-dom": "^4.3.1",
"react-scripts": "5.0.0",
"redux": "^4.1.2",
"redux-devtools-extension": "^2.13.9",
"redux-thunk": "^2.4.1",
"uuid": "^8.3.2",
"web-vitals": "^2.1.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://localhost:5000"
}
It was a loading issue. The loading value does not change. The value remained true,
Therefore, I removed the loading check from the render. This worked.
const PrivateRoute = ({
component: Component,
auth: { isAuthenticated },
...rest
}) => (
<Route
{...rest}
render={props =>
!isAuthenticated ? (
<Redirect to='/login' />
) : (
<Component {...props} />
)
}
/>
);

My window in Electron doesn't appear no matter what I do, there is something wrong with my code?

Firstly I'm using Vuejs and Electron, the package.json will be in the end of this post.
I'm trying to use this listener to show my window as the Electron's documentation recommend.
win.once("ready-to-show", () => win.show());
But it seems that this never fired, only if I manually get the variable win and call the function show().
Below is my background.js (The file that runs the Electron's main process) file and my windowManager.js file (The file that I've created for build my windows and return them, I import this file into background.js)
//background.js
"use strict";
import { app, protocol, BrowserWindow, ipcMain } from "electron";
import installExtension, { VUEJS_DEVTOOLS } from "electron-devtools-installer";
import { windowManager } from "./backend/windowManager.js";
const isDevelopment = process.env.NODE_ENV !== "production";
let winHome, winMain;
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
{ scheme: "app", privileges: { secure: true, standard: true } },
]);
// Quit when all windows are closed.
app.on("window-all-closed", () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", async () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
winHome = await windowManager.createHomeWindow();
winHome.show();
}
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", async () => {
if (isDevelopment && !process.env.IS_TEST) {
// Install Vue Devtools
try {
await installExtension(VUEJS_DEVTOOLS);
} catch (e) {
console.error("Vue Devtools failed to install:", e.toString());
}
}
winHome = await windowManager.createHomeWindow();
winHome.show();
});
// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
if (process.platform === "win32") {
process.on("message", (data) => {
if (data === "graceful-exit") {
app.quit();
}
});
} else {
process.on("SIGTERM", () => {
app.quit();
});
}
}
// IPC callback listeners
const closeWindow = () => {
BrowserWindow.getFocusedWindow().close();
};
const openMainWindow = async () => {
winMain = await windowManager.createMainWindow();
winHome.close();
};
// Setting the IPC listeners
ipcMain.on("close-window", closeWindow);
ipcMain.on("open-main-window", openMainWindow);
//windowManager.js
import { BrowserWindow } from "electron";
import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
import * as path from "path";
export const windowManager = {
async createWindow(sizeProperties, settings, router = null) {
let win;
// Create the browser window.
win = new BrowserWindow({
...sizeProperties,
...settings,
webPreferences: {
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
preload: path.join(__dirname, "preload.js"),
},
});
//Checking with was sent some router
router = router ? `/#/${router}` : "";
try {
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
await win.loadURL(`${process.env.WEBPACK_DEV_SERVER_URL}${router}`);
if (!process.env.IS_TEST) win.webContents.openDevTools();
} else {
createProtocol("app");
// Load the index.html when not in development
await win.loadURL(`app://./index.html${router}`);
}
} catch (error) {
console.error(error);
}
//Setting the default behavior for window
win.once("ready-to-show", () => {
win.show();
});
win.on("closed", () => {
win.destroy();
});
//TODO Check if this line is necessary
win.show();
return win;
},
async createHomeWindow() {
return await this.createWindow(
{
width: 706,
height: 550,
},
{
frame: false, //Remove frame to hide default menu
resizable: false,
show: false, //Don't show at the begin
}
);
},
async createMainWindow() {
let win = await this.createWindow(
{
width: 800,
height: 550,
},
{
frame: false, //Remove frame to hide default menu
show: false, //Don't show at the begin
},
"main"
);
//Extra window behavior
win.maximize();
return win;
},
};
And the package.json
{
"name": "simulans",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"electron:build": "vue-cli-service electron:build",
"electron:serve": "vue-cli-service electron:serve",
"postinstall": "electron-builder install-app-deps",
"postuninstall": "electron-builder install-app-deps"
},
"main": "background.js",
"dependencies": {
"core-js": "^3.6.5",
"vue": "^2.6.11",
"vue-router": "^3.0.3",
"vuex": "^3.4.0"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-plugin-vuex": "~4.5.0",
"#vue/cli-service": "^3.0.5",
"#vue/eslint-config-prettier": "^6.0.0",
"babel-eslint": "^10.1.0",
"electron": "^13.0.1",
"electron-devtools-installer": "^3.1.0",
"eslint": "^6.7.2",
"eslint-plugin-prettier": "^3.3.1",
"eslint-plugin-vue": "^6.2.2",
"prettier": "^2.2.1",
"vue-cli-plugin-electron-builder": "~2.0.0",
"vue-template-compiler": "^2.6.11"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended",
"#vue/prettier"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {
"prettier/prettier": 0
}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
You are using an asynchronous function for creating your browser window. This is not a problem, but here, you are binding your BrowserWindow events after you make your asynchonous call.
This basically means that you are waiting for your try/catch block to end before binding your ready-to-show event. I suspect that the event is fired before the asynchronous call ends.
If this is the case, the solution is just to place your win.once("ready-to-show", () => win.show()); before your try { ... } catch ... block.

React Webpack add new npm package

How to add a new npm package with webpack? I can't understand the main idea.
Example, let's use npm install react-ripple-effect --save-dev from npm package here
After that, a bunch of files appears in /node_modules/react-ripple-effect
My structure:
>ReactApp
>>App
>>>components
----Arctic.jsx
----ArcticForm.jsx
----ArcticMessage.jsx
----Main.jsx
----Nav.jsx
>>>styles
----app.scss
---app.jsx
>>node_modules
...
>>public
---bundle.js
---index.html
--package.json
--server.js
--webpack.config.js
package.json
{
"name": "react-app",
"version": "1.0.0",
"description": "xxx",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "xxx",
"license": "xxx",
"dependencies": {
"express": "^4.14.0",
"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-router": "^2.0.0"
},
"devDependencies": {
"babel-core": "^6.5.1",
"babel-loader": "^6.2.2",
"babel-preset-es2015": "^6.5.0",
"babel-preset-react": "^6.5.0",
"css-loader": "^0.23.1",
"foundation-sites": "^6.2.0",
"jquery": "^2.2.1",
"node-sass": "^3.4.2",
"react-ripple-effect": "^1.0.4",
"sass-loader": "^3.1.2",
"script-loader": "^0.6.1",
"style-loader": "^0.13.0",
"webpack": "^1.12.13"
}
}
webpack.config.js
var webpack = require('webpack');
module.exports = {
entry: [
'script!jquery/dist/jquery.min.js',
'script!foundation-sites/dist/foundation.min.js',
'./app/app.jsx'
],
externals: {
jquery: 'jQuery'
},
plugins: [
new webpack.ProvidePlugin({
'$': 'jquery',
'jQuery': 'jquery'
})
],
output: {
path: __dirname,
filename: './public/bundle.js'
},
resolve: {
root: __dirname,
alias: {
Main: 'app/components/Main.jsx',
Nav: 'app/components/Nav.jsx',
Arctic: 'app/components/Arctic.jsx',
ArcticForm: 'app/components/ArcticForm.jsx',
ArcticMessage: 'app/components/ArcticMessage.jsx',
applicationStyles: 'app/styles/app.scss'
},
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
},
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/
}
]
}
};
app.jsx
var React = require('react');
var ReactDOM = require('react-dom');
var {Route, Router, IndexRoute, hashHistory} = require('react-router');
var Main = require('Main');
var Nav = require('Nav');
var Arctic = require('Arctic');
// Load foundation
require('style!css!foundation-sites/dist/foundation.min.css')
$(document).foundation();
// App css
require('style!css!sass!applicationStyles')
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={Main}>
<IndexRoute component={Arctic}/>
</Route>
</Router>,
document.getElementById('app')
);
main.jsx
var React = require('react');
var Nav = require('Nav');
var Main = (props) => {
return (
<div>
<Nav />
<div className="row">
<div className="columns medium-6 large-4 small-centered">
{props.children}
</div>
</div>
</div>
);
}
module.exports = Main;
arctic.jsx
var React = require('react');
var ArcticForm = require('ArcticForm');
var ArcticMessage = require('ArcticMessage');
var Arctic = React.createClass({
getDefaultProps: function () {
return {
name: "polar bear!"
};
},
getInitialState: function () {
return {
name: this.props.name
};
},
handleNewData: function (updates) {
this.setState(updates);
},
render: function(){
var name = this.state.name;
return (
<div>
<h1 className="text-center">Arctic</h1>
<ArcticForm onNewData={this.handleNewData}/>
<ArcticMessage name={name}/>
</div>
)
}
});
module.exports = Arctic;
ArcticForm.jsx
var React = require('react');
var ArcticForm = React.createClass({
onFormSubmit: function (e) {
e.preventDefault();
var updates = {};
var name = this.refs.name.value;
if (name.length > 0) {
this.refs.name.value = '';
updates.name = name;
}
this.props.onNewData(updates);
},
render: function () {
return (
<div>
<form onSubmit={this.onFormSubmit}>
<input type="text" ref="name" placeholder="Name" />
<button type="submit" className="button expanded hollow">
Submit
</button>
</form>
</div>
);
}
});
module.exports = ArcticForm;
ArcticMessage.jsx
var React = require('react');
var ArcticForm = require('ArcticForm');
var ArcticMessage = React.createClass({
render: function () {
var name = this.props.name;
return (
<h3 className="text-center">Hi {name}</h3>
);
}
});
module.exports = ArcticMessage;
The package instructions tell me to include this, but where and how? And how to include that in webpack?
import React from 'react';
import ReactDOM from 'react-dom';
import { RippleButton } from 'react-ripple-effect';
class App extends React.Component {
render(){
return(
<RippleButton>Click On Me!</RippleButton>
)
}
}
ReactDOM.render(<App />, document.getElementById("app"))
You don't import in webpack...Webpack is responsible to read your source and bundle all necessary modules.
The idea is:
You install a module using NPM.
You use inside your source code using import <module>
When bulding with webpack, it reads your source code, find that import and bundles it.

Resources