So I have a file called Context.js which looks like the following:
const AppContext = createContext({
// ... scheme colour palette
color1: '#ADBDDB',
color2: '#7F8EB2',
color3: '#546287',
color4: '#384366',
// ... grey colour palette
grey1: '#FFFFFF',
grey7: '#2A3033',
// ... Nexus back-end constants
nexusIP: '126.0.0.2',
I want to import that file onto another component and use the "nexusIP" in that component. However, it is giving me issues. This is what I tried to do:
import Context from '../context/AppContext';
import React, { useContext, useState , Component } from 'react';
const { nexusIP, color5, grey1 } = useContext(AppContext);
class TempsAndTime extends React.Component {
constructor(props){
super(props);
this.state = {
bedTempDisplay: props.bedTemp,
bedTempUser: props.bedTemp,
hotEndTempDisplay: props.hotEndTemp,
hotEndTempUser: props.hotEndTemp,
pcBootTimeStamp: props.pcBootTimeStamp,
pcId: props.pcId,
hotEndTempCondition: null,
bedTempCondition: null
}
}
render() {
const { classes } = this.props;
let bedTempIcon;
let hotEndTempIcon;
return (
<div className={classes.container} >
<div className={classes.timeContainer} >
<Typography className={classes.timeElapsed}>
Time elapsed
</Typography>
</div>
<div>
);
}}
So I tried to destructure the value from that other Context.js file into this file but it was not letting me to do so. Any ideas?
according to React documentation you can't use hook inside a class component nor outside of a functional component. so, try with functional component and definitely call inside the component, otherwise consume the context as React suggest with render props
Related
My Loading component:
import React from 'react'
export default class Loading extends React.Component {
constructor(props) {
super(props)
this.state = {
display: 'none'
}
}
render() {
return (
<div className="loading" style={{display: this.state.display}}>
<span></span>
</div>
)
}
}
And I want change display from App.js
Loading.setState ...
Or
var lng = new Loading()
lng.setState ...
Both of them not work
I want can change state from another class or function
If you want to change display from App.js:
Pass it as prop to Loading component, and keep the state at App.js.
pass some prop from App.js and when it changes - change the state
of display in App.js
Use some global state/store manager like Redux or built-in useContext react-hook, in this case you will be able to change from any component connected to store
Solution sample
A simple solution can be found in a code sandbox example.
im trying to render data into an array so that the data can be viewed in a chart in react native.
There seems to be an issue regarding maximum
import React, { Component } from 'react';
import { View,Button,Text } from 'react-native';
import { LineChart, XAxis, Grid } from 'react-native-svg-charts'
import n_data from './data'
class MyComponent extends Component {
constructor() {
super()
this.state = {data:[]}
}
render() {
const restructuredData = n_data.map( (name) => this.setState({data:name.volume}) )
return (
<View>
<Text> {this.state.data} </Text>
</View>
);
}
}
export default MyComponent;
my sample data is in n_data and looks like this
const n_data = [{"timestamp":"2011-08-18T00:00:00Z","volume":"5","spot_volume":"5","derivative_volume":"0"}]
Try formatting the data outside of the component (no need to use setState here) and then just set it as your inital state inside the constructor.
this.setState() usually triggers a render. When you call it directly from inside the render function there will probably be an endless loop.
The other thing is that your trying to render an array as Rohit already mentioned.
The error you are having because you are resetting state Ina render function which will try to re-render the component. You will need to modify your component, here is a quick example
import React, { Component } from 'react';
import { View,Button,Text } from 'react-native';
import { LineChart, XAxis, Grid } from 'react-native-svg-charts'
import n_data from './data'
class MyComponent extends Component {
constructor() {
super()
let data= null;
n_data.map(name=>{data=name.volume});
this.state = {data}
}
render() {
return (
<View>
<Text> {this.state.data} </Text>
</View>
);
}
}
export default MyComponent;
You can use the map function like this. Your restructuredData will eventually lead to a Maximum call depth error as the setState method is called multiple times and will cause the component to re-render equal to the length of your n_data array.
<View>
{n_data &&
n_data.map((item) => (
<Text key = {item.volume}>{item.volume}</Text>
))}
</View>
Also, you're trying to render an array as a Text component here
<Text> {this.state.data} </Text>
which is not correct.
Update:
This is how you can update the state
restructuredData = n_data => {
let updated_n_data = [];
// Object.values(objName) gives the values of an object
Object.values(n_data).map(item => {
updated_n_data = updated_n_data.concat(item.volume);
});
this.setState({
data: updated_n_data,
});
};
I'm trying to have access to an element from an array of objects in the React state. This array is the result of a fetch command. I know that I need to write a "map" ,but the map will result in getting the whole elements of the array.
Here's the code I have written :
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
// function App() {
// } instead we'll use class component
class App extends Component{
constructor(){
super();
this.state = {
guys:[]
}
};
componentDidMount(){
fetch('https://jsonplaceholder.typicode.com/users')
.then(response=>response.json())
.then(user=>this.setState({guys:user}))
}
render(){
//we'll add the return part from the stateless component
return (
<div className="App">
{this.state.guys.map(guy=>(
<h2 > {guy.email} </h2>
))}
</div>
);
}
}
export default App;
The result of the code above is :
Sincere#april.biz
Shanna#melissa.tv
Nathan#yesenia.net
Julianne.OConner#kory.org
Lucio_Hettinger#annie.ca
Karley_Dach#jasper.info
Telly.Hoeger#billy.biz
Sherwood#rosamond.me
Chaim_McDermott#dana.io
Rey.Padberg#karina.biz
However,I would like to access to only one element,for example, the ideal outcome must be Shanna#melissa.tv.
I have tried <h1>this.state.guys[1].email</h1>, but this approach seems to be ineffective and I know I should do sth else. Do you have any idea on how to access and manipulate only one (or some) of the states?
I got an app that is working on react using a class component, i found a code of a feature that i would like to add to my code but it's made using a functional component. The code is here https://codesandbox.io/s/framer-motion-animate-in-view-gqcc8 but the relevant part is this.
import { useInView } from "react-intersection-observer";
import { motion, useAnimation } from "framer-motion";
import "./styles.css";
function Box() {
const controls = useAnimation();
const [ref, inView] = useInView();
useEffect(() => {
if (inView) {
controls.start("visible");
}
}, [controls, inView]);
I don't know how to add that controls variable in my class component
class App extends Component {
constructor(props) {
super(props);
this.state = {
curtains: null,
loading: true,
renderNav: false
};
}
Should i add it on my state? i don't understand how to make it works in class component
You can't use hooks inside of a class component. What you can do is to write a little wrapper that exposes the ref and controls in a render prop:
const Controls = ({children}) => {
const controls = useAnimation();
const [ref, inView] = useInView();
useEffect(() => {
if (inView) {
controls.start("visible");
}
}, [controls, inView]);
return children(ref, controls);
};
Then you can use it like this:
class App extends Component {
// ...
render() {
return (
<Controls>
{(ref, controls) => (
<motion.div ref={ref} animate={controls}>
{/* content */}
</motion.div>
)}
</Controls>
);
}
}
Lets say you have
const functionalComponent=()=>{
return <h1>Functional componenet</h1>
}
and you want to change it to class component
use this import at the top:
import React,{Component} from "react";
and change your code to something like this:
Class functionalComponent extends Component{
state={}
render(){
return <h1>functional component</h1>;
}
}
your functional component is now changed to class component.
And to use it in your existing class component , you don't need to change your functional component to class component unless you require local state.
with the introduction of react hooks that's also changed i.e, you don't have to change your functional component to class component if you plan to use hooks.
In your code : useEffect is a hook and you can't use it inside a class component.
I would recommend simply importing the functional component inside your class component and if you have to pass some value , you can pass it as a prop.
And as far as importing your functional component is concerned:
import React,{Component} from "react";
import Box from "./Box.js";
class App extends Component {
constructor(props) {
super(props);
this.state = {
curtains: null,
loading: true,
renderNav: false
};
render(){
return(<Box/>);
}
}
You can also use functional components anywhere like a class component. Btw is also using so no need to worry about the thing that you cannot use state in it.
Use:
<Box props={props}/>
I'm trying to implement methods to the React import of PESDK (PhotoEditorSDK).
I have an App.js that imports Header, BodyLeft and BodyMiddle without relation between them.
BodyMiddle.js is a template component that renders :
// src/components/BodyMiddle/index.js
import React, { Component } from "react";
import "./BodyMiddle.css";
class BodyMiddle extends Component {
constructor(props){
super(props);
}
handleClick(e) {
e.preventDefault();
// Nothing yet
}
render() {
return (
<div id="BodyMiddle">
<div><button id="resetEditor" onClick={(e) => this.handleClick(e)}>Reset Editor</button></div>
<div class="photo-editor-view"></div>
</div>
);
}
}
export default BodyMiddle;
PhotoEditor.js is the component that calls the PESDK :
// src/components/PhotoEditor/index.js
import React from 'react'
import ReactDOM from 'react-dom'
window.React = React
window.ReactDOM = ReactDOM
import "./PhotoEditor.css";
import "photoeditorsdk/css/PhotoEditorSDK.UI.ReactUI.min.css";
import PhotoEditorUI from 'photoeditorsdk/react-ui'
class PhotoEditor extends React.Component {
constructor(props){
super(props);
}
resetEditor(){
// Empty the image
return this.editor.ui.setImage(new Image());
}
render() {
const { ReactComponent } = PhotoEditorUI;
return (
<div>
<ReactComponent
ref={c => this.editor = c}
license='licence_removed_for_snippet'
assets={{
baseUrl: './node_modules/photoeditorsdk/assets'
}}
editor={{image: this.props.image }}
style={{
width: "100%",
height: 576
}} />
</div>)
}
}
export default PhotoEditor;
Note that the photo-editor-view div class is rendered in BodyLeft.js, by calling the following code and it works well:
ReactDOM.render(<PhotoEditor ref={this.child} image={image} />, container);
Where container is (and I pass an image somewhere else) :
const container = document.querySelector('.photo-editor-view');
What I'm trying to achieve
I would like to keep the reset Button inside BodyMiddle, which is independant and called from App.js, in order to call the PhotoEditor component on the method resetEditor() from anywhere in my app.
That way I could have separated template files that interract with each other.
I've done research and I did not really find an answer yet, I know that React might not be the lib for that, but what are the options ? I see more and more React live apps running with a lot of components interacting, I'm curious.
Thank you for your time !
Best regards
You can use ref on PhotoEditor and save that ref in App, and in the App you can have a method called onResetEditor which calls the ref.resetEditor.
Now you can pass onResetEditor to BodyMiddle or any other component.
Read more about refs in React https://reactjs.org/docs/refs-and-the-dom.html