I'm new in React.JS, I'm currently using it with Node and I'm having the following issue:
I'm using a button from Material-UI (Google's interface assets - buttons, menus, etc) and I have the button's styles defined inside a const that is ran through a function (because it's how it is declared in their own website, I'm not sure why I need to have a function instead of just calling the const).
What I'm doing is customizing the margin of the button I'm importing and setting the display to 'none' on the browser's pre-defined button so it disappears.
I inserted the const with the styles values inside a component called HookApi.js and this is its content:
import React, { useState } from 'react';
import '../App.css';
import { makeStyles } from '#material-ui/core/styles';
import Button from '#material-ui/core/Button';
const useStyles = makeStyles((theme) => ({
root: {
'& > *': {
margin: theme.spacing(1),
},
},
input: {
display: 'none',
},
}));
export function UploadButtons() {
const classes = useStyles();
}
And this is what I have inside my Gallery.js (which is replacing my App.js for testing purposes)
import React, { useState } from 'react';
import './App.css';
import { makeStyles } from '#material-ui/core/styles';
import Button from '#material-ui/core/Button';
import HookApi from './constants/HookApi';
import { classes } from './constants/HookApi';
class Gallery extends React.Component{
constructor(props) {
super(props);
}
render() {
return(
<div className={classes.root}>
<input
accept="image/*"
className={classes.input}
id="contained-button-file"
multiple
type="file"
/>
<label htmlFor="contained-button-file">
<Button variant="contained" color="primary" component="span">
Upload
</Button>
</label>
</div>
);
}
}
export default Gallery;
I'm not sure if I'm importing the const the wrong way in my Gallery.js but it gives me the following error when I'm rendering the page
'classes' is not exported from 'HookApi' - image
Instead of exporting a const, you can try to export the function.
Gallery.js
import UploadButtons from './constants/HookApi';
render() {
const {input} = this.props.UploadButtons();
//...other logic
(<input
accept="image/*"
className={input}
id="contained-button-file"
multiple
type="file"
/>)
}
}
Related
Hey all im looking for help. im having some trouble with passing data from one child component to another child component using the context api. But i get this typeError instead, i tried a few searches so far without much luck. if anyone can't point me in the right direction it would be much appreciated!
thanks
CurrencyProvider.js
import { React, Component} from 'react';
export const MContext = React.createContext('');
class CurrencyProvider extends Component {
constructor() {
super()
this.state = {
setinputValue: (value) => this.setState({ inputValue: value })
}
}
render() {
return (
<MContext.Provider value={this.state}>
{this.props.children}
</MContext.Provider>)
}
}
export default CurrencyProvider;
Dropdown.js
import { useQuery, gql } from "#apollo/client";
import { useState } from "react";
import './Dropdown.scss';
import { MContext } from "../CurrencyProvider";
const EXCHANGE_RATES = gql`
query GetExchangeRates {
rates(currency: "AUD") {
currency
rate
name
}
}
`;
function Dropdown() {
const [isToggled, setToggle] = useState(false);
const { data, loading, error } = useQuery(EXCHANGE_RATES);
if (loading) {
return <div>loading</div>;
}
if (error) {
return <div>{error}</div>;
}
return (
<div className="custom-dropdown">
<ul className={`dropdown-menu ${isToggled ? 'open':''}`}>
<li value="0" className="first-item" onClick={() => setToggle(!isToggled)} onKeyPress={() => setToggle(!isToggled)} tabIndex="0">Select Currency:</li>
{data.rates.map(({ currency, rate, name },index) => (
<MContext.Consumer>
{(context) => (
<li className="list-item" key={index} data={rate} tabIndex="0" onClick={()=>{context.setinputValue(rate)}}> <span>{name}: {currency}</span></li>
)}
</MContext.Consumer>
))}
</ul>
</div>
);
}
export default Dropdown;
Input.js
import './Input.scss';
import { MContext } from "../CurrencyProvider";
function Input() {
return(
<MContext.Consumer>
{(context) => (
<input value={context.state.inputValue} />
)}
</MContext.Consumer>
);
}
export default Input;
CurrencyContainer.js
import Dropdown from '../Dropdown/Dropdown';
import Input from '../Input/Input';
import './CurrencyContainer.scss';
import CurrencyProvider from '../CurrencyProvider';
function CurrencyContainer() {
return (
<div className='currency-container'>
<h1 >Select Items</h1>
<div className="currency-wrapper">
<CurrencyProvider>
<div><Input /></div>
<div><Dropdown /></div>
<div><Dropdown /></div>
</CurrencyProvider>
</div>
</div>
);
}
export default CurrencyContainer;
App.js
import logo from './logo.svg';
import './App.scss';
import { client } from "./ApolloClient/client";
import { ApolloProvider } from '#apollo/client';
import CurrencyContainer from './CurrencyContainer/CurrencyContainer';
function App() {
return (
<ApolloProvider client={client}>
<div className="App">
<img src={logo} className="App-logo" alt="logo" />
<CurrencyContainer />
</div>
</ApolloProvider>
);
}
export default App;
Why don't you try placing something more in the likes of this in a separate file mcontext.context.jsx:
import { createContext } from "react";
const MContext = createContext('');
export default MContext;
Then you can import it and
get values by importing your newly created context, the useContext hook and adding something like this to the top of a functional component which is encapsulated inside a MContext.Provider node:
const val = useContext(MContext);
set values:
<MContext.Provider value={mcontextValue}>
</MContext.Provider>
All children inside your MContext.Provider node and their children will have access to your MContext value given you get it as I showed you in the 1st part of the answer.
Your React import is incorrect. Change it to:
import React, {Component} from 'react';
React is the default export, not a named export.
React package doesn't have a named import called React, it has a default import that people generally use React for, so you should change this line
import { React, Component } from 'react';
to this
import React, { Component } from 'react';
If you use React 17+, you don't need to import React from 'react'; anymore, you can remove any mentioning of React from your import, so your import will look like this
import { createContext } from 'react';
But you have to turn off the lint rules for this import in your .eslintrc.json file like so
{
"rules": {
...
"react/jsx-uses-react": "off",
"react/react-in-jsx-scope": "off"
}
}
So react-admin seems to have a feature where if you're idle for a little while and come back it will reload the data, presumably to make sure you're looking at the most up to date version of a record.
This is causing some issues for my editing feature that has some custom components. Is there a way to disable this auto-reload feature?
The auto-refresh is triggered by the loading indicator (the spinner icon that you see in the top right part of the app bar).
You can disable the auto-refresh by replacing the loading indicator by your own.
import * as React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { useSelector } from 'react-redux';
import { makeStyles } from '#material-ui/core/styles';
import CircularProgress from '#material-ui/core/CircularProgress';
import { useRefreshWhenVisible, RefreshIconButton } from 'react-admin';
const useStyles = makeStyles(
{
loader: {
margin: 14,
},
loadedIcon: {},
},
{ name: 'RaLoadingIndicator' }
);
const LoadingIndicator = props => {
const { classes: classesOverride, className, ...rest } = props;
useRefreshWhenVisible(); // <= comment this line to disable auto-refresh
const loading = useSelector(state => state.admin.loading > 0);
const classes = useStyles(props);
return loading ? (
<CircularProgress
className={classNames('app-loader', classes.loader, className)}
color="inherit"
size={18}
thickness={5}
{...rest}
/>
) : (
<RefreshIconButton className={classes.loadedIcon} />
);
};
LoadingIndicator.propTypes = {
classes: PropTypes.object,
className: PropTypes.string,
width: PropTypes.string,
};
export default LoadingIndicator;
You'll also need to put this button in a custom AppBar, inject your AppBar in a custom Layout, and use that Layout in your Admin, as explained in the react-admin Theming documentation.
I was able to turn off auto-refresh by dispatching the setAutomaticRefresh action from react-admin:
import { setAutomaticRefresh } from 'react-admin';
import { useDispatch } from 'react-redux';
// inside component
const dispatch = useDispatch();
dispatch(setAutomaticRefresh(false))
This action was added here as part of release 3.8.2.
I am learning ReactNative, and now I'm looking into how to organize the files (for now I am going to create a folder for each page, each with an index, functions and styles file). For some reason, though, I am not being able to import information to index.js, can't use the styles or functions, when I open the page, it doesn't return the func method.
I am wondering whether I am using import wrong. Using import { MenuFunctions} from './Menu' has resulted in an error saying nothing was imported, this error no longer appears, but nothing is being returned still.
This is my code, index, Menu and styles are all in the same folder.
index.js
import React from 'react';
import MenuFunctions from './Menu';
import MenuStyles from './styles'
import { Text, View } from 'react-native';
export default class MenuPage extends React.Component {
render(){
return(
<View>
<Text> Text: {MenuFunctions.func} </Text>
</View>
);
}
}
Menu.js
import React from 'react';
export default class MenuFunctions extends React.Component{
constructor(props){
super(props);
}
func = () => {return "Hello, World!"};
}
styles.js
import React from 'react';
import { StyleSheet } from 'react-native';
export default class MenuStyles extends React.Component{
styles = StyleSheet.create({
text: {
color: "red",
}
});
}
Menu.js and styles.js shouldn't be React.Component and you forgot to call to Func method, () is missing.
React.Component is a UI component only which include a render method that returns JSX element.
Your code should look like that:
index.js
import React from 'react';
import MenuFunctions from './Menu';
import MenuStyles from './styles';
import {Text, View} from 'react-native';
export default class MenuPage extends React.Component {
render() {
return (
<View>
<Text> Text: {MenuFunctions.func()} </Text>
</View>
);
}
}
Menu.js
import React from 'react';
class MenuFunctions {
func = () => {
return 'Hello, World!';
};
}
export default new MenuFunctions();
styles.js
import {StyleSheet} from 'react-native';
export default styles = StyleSheet.create({
text: {
color: Colors.red30,
}
});
The problem is that you are trying to import Menu.js using import MenuFunctions from './Menu' when you had to specify the file itself:'./Menu/Menu.js'. (remember to call the function using parentheses class.function())
Also, whenever you export as default you don't have to use curly braces {}
If you are wondering about your project structure, you can use the following as a common structure to create projects. Let's say you have the following
- index.js
- src
- assets
- screens
- MenuScreen
- components
- services
- menu
- index.js //this is Menu.js
- android
- ios
NOTE
Do not extend React.Component if you are not exporting a component.
You need an object to perform the function of the class you created.
Then declare and use the constructor.
index.js
import React from 'react';
import MenuFunctions from './Menu';
import MenuStyles from './styles'
import { Text, View } from 'react-native';
export default class MenuPage extends React.Component {
constructor(props){
super(props);
this.menu = new MenuFunctions()
MemuStyle = new MenuStyles()
}
render(){
return(
<View>
<Text style={MemuStyle.styles.text}> Text: {this.menu.func()}</Text>
</View>
);
}
}
Menu.js
import React from 'react';
export default class MenuFunctions extends React.Component {
func(){
return 'Hello, World!';
}
}
styles.js
import { StyleSheet } from 'react-native';
export default class MenuStyles extends React.Component {
styles = StyleSheet.create({
text: {
color: "red",
}
});
}
NOTE: The features you intend to use do not necessarily have to inherit React.
Hello i'm getting this error when tried to implement a header containing a logout button. The error i'm getting is to check the render method.But can't figure out the error.The file in which i'm getting error is the following
import React from "react";
import {
ScrollView,
View,
StyleSheet,
Image,
Text,
Button,
Title,
Header,
AsyncStorage,
Icon
} from "react-native";
import {
RkText,
} from "react-native-ui-kitten";
import Card from "./Card";
import CardSection from "./CardSection";
import Login from './Login';
export class GridV2 extends React.Component {
onPressLogout(){
AsyncStorage.removeItem(token);
}
render() {
return (
<View>
<Header style={{backgroundColor:'#B00000'}}>
<Button
transparent
onPress={() => this.onPressLogout()}
>
<Icon
style= {{color: '#ffffff', fontSize: 25, paddingTop:0}}
name="bars" />
</Button>
</Header>
<Card>
<CardSection>
</CardSection>
</Card>
</View>
);
}
}
I'm importing this GridV2 in my Login screen.Login screen is as follows. What is the mistake in this code?Please help..
import React, {Component} from 'react';
import { Container,
Title,
InputGroup,
Input,
Button,
Text,
View,
Spinner,
Item,
Label,
} from 'native-base';
import {
StyleSheet,
Image,
Navigator,
TouchableOpacity,
AsyncStorage,
Linking
} from 'react-native';
import QASection from './QASection';
import GridV2 from './grid2';
class Login extends Component{
state = { userdetail: [] };
constructor(props) {
super(props);
this.initialState = {
isLoading: false,
error: null,
username: '',
password: ''
};
this.state = this.initialState;
}
render() {
return();
}
You got your exports/imports wrong. Please remove all unused imports and check if the ones you are importing are in the package they are imported from. For example, as far as I know, there is no such thing as Header component in react-native (DOC
You should import GridV2 using named import:
import { GridV2 } from './grid2';
or export is as a default first:
export default class GridV2 extends React.Component {
Please check if your other imports are intact (you have correct filenames etc.).
This link explains exports/imports well.
Also you should not return like this return (); from render method. Instead return null like below:
return (null);
"Element type is invalid" I still keep getting this error and don't know what to do. Tried <form> and <Form> still same. Please help:
This is my AzForm.js saved at: "./components/testComponent"
import React from 'react'
import { Provider } from 'react-redux'
import { Container, Content, Text, Form } from 'native-base';
//import { createStore } from 'redux' //NOT sure whether I need it, but I still get the same error
import { reduxForm } from 'redux-form'
const SignInForm = props => {
return (
<Form>
</Form>
);
};
export default reduxForm({
form: 'simple' // a unique identifier for this form
})(SignInForm)
and this is an extract from index.js
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Image } from 'react-native';
import { SignInForm } from "./components/AzForm";
export class HomeScreen extends Component {
render() {
return (
<SignInForm />
);
}
}
Change
export class HomeScreen
to
export default class HomeScreen`
When you export without the default, the component that is exported becomes what is known as a named export (you can have many of these per file). You would import these as import {HomeScreen} from 'HomeScreen'
The React convention is to one component per file. This is achieved by using the export default option as provided above. You would then import it using import HomeScreen from 'HomeScreen';