I try to get used to reflux and forked a example repo. My full code is here [ https://github.com/svenhornberg/react-starterkit ]
I want to create a timer component which gets the current time from a timestore, but it is not working. The DevTools does not show any errors. This must be some newbie mistakes, but I do not find them.
Edit1: I added a line in home //edit1
Edit2: I think the mistake may be in componentDidMount in home.jsx
FIXED I need to trigger my time, see my answer.
Store
import Reflux from 'reflux';
import TimeActions from '../actions/timeActions';
var TimeStore = Reflux.createStore({
listenables: timeActions,
init() {
this.time = '';
},
onCurrenttime() {
this.time = '13:47';
}
});
export default TimeStore;
Actions
import Reflux from 'reflux';
var TimeActions = Reflux.createActions([
'currenttime'
]);
export default TimeActions;
Component
import React from 'react';
class Timer extends React.Component {
constructor(){
super();
}
render() {
var time = this.props.time;
return (
<div>
{ time }
</div>
);
}
}
Timer.propTypes = {
time : React.PropTypes.string
}
export default Timer;
I wanted to use the timer component in the home.jsx
import React from 'react';
import ItemList from '../components/itemList.jsx';
import ItemStore from '../stores/itemStore';
import ItemActions from '../actions/itemActions';
import Timer from '../components/timer.jsx';
import TimeStore from '../stores/timeStore';
import TimeActions from '../actions/timeActions';
class Home extends React.Component {
constructor(props){
super(props);
this.state = {
items : [],
loading: false,
time : '' //edit1
};
}
componentDidMount() {
this.unsubscribe = ItemStore.listen(this.onStatusChange.bind(this));
this.unsubscribe = TimeStore.listen(this.onStatusChange.bind(this));
ItemActions.loadItems();
TimeActions.currenttime();
}
componentWillUnmount() {
this.unsubscribe();
}
onStatusChange(state) {
this.setState(state);
}
render() {
return (
<div>
<h1>Home Area</h1>
<ItemList { ...this.state } />
<Timer { ...this.state } />
</div>
);
}
}
export default Home;
I fixed it thanks to: How to Make React.js component listen to a store in Reflux
I have to trigger my time:
var TimeStore = Reflux.createStore({
listenables: TimeActions,
init() {
this.time = '';
},
onCurrenttime() {
this.trigger({
time : '13:47'
});
}
});
Related
2 components :- ClickCounter, mouseHoverCounter !
1 HOC component to do the counting work.
earlier I was counting the click and mouse hover by writing separate counter method in each component(cliccounter,mousehovecounter),
but
now, I'm trying to pass the component into hoc counter & get the new component with only one change , where I'm passing a props to originalComponent and returning it to see the behavior but its now working...
import React, { Component } from 'react'
import updatedComponent from './hocCounter'
class ClickCounter extends Component {
constructor(props) {
super(props)
this.state = {
counter:0
}
}
ClickCounterHandler = () =>{
this.setState((prevState)=>{
return {counter:prevState.counter+1}
})
}
render() {
const count=this.state.counter
return (
<div>
<button onClick={this.ClickCounterHandler}>{this.props.name} Clicked {count} Times</button>
</div>
)
}
}
export default updatedComponent(ClickCounter)
import React, { Component } from 'react'
import updatedComponent from './hocCounter'
class HoverMouseCounter extends Component {
constructor(props) {
super(props)
this.state = {
counter:0
}
}
MouseOverCounter(){
this.setState((prevState)=>{
return {counter:prevState.counter+1}
})
}
render() {
const count=this.state.counter
return (
<div>
<h1 onMouseOver={this.MouseOverCounter.bind(this)}>{this.props.name} Hovered For {count} Time(s)</h1>
</div>
)
}
}
export default updatedComponent(HoverMouseCounter)
import React from 'react'
const updatedComponent = originalComponent => {
class newComponent extends React.Component {
render(){
return <originalComponent name='Harsh'/>
}
}
return newComponent
}
export default updatedComponent
In App.js, I'm returning
<ClickCounter></ClickCounter>
<HoverMouseCounter></HoverMouseCounter>
this only !
Check the error in the console,
index.js:1 Warning: <originalComponent /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements. at originalComponent
This means You are using the small letter in originalComponent
React components are expected to start with a capital letter
Try this in you HOC component
import React from 'react'
const updatedComponent = OriginalComponent => {
class NewComponent extends React.Component {
render(){
return <OriginalComponent name='Harsh'/>
}
}
return NewComponent
}
export default updatedComponent
I decided to try Mobx and faced the problem of the component's lack of response to a changing field in the repository. I looked at similar topics, but I still don't understand what the problem is. If you print the property value to the console after the change, you see the actual result.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from "mobx-react";
import AppStore from "./AppStore";
import App from './App';
ReactDOM.render(
<React.StrictMode>
<Provider AppStore={AppStore}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
App.js
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
#inject('AppStore')
#observer class App extends Component {
render() {
const { AppStore } = this.props;
console.log(AppStore);
return(
<div className="App">
{ this.props.AppStore.counter }
<hr/>
<button onClick={this.props.AppStore.increment}>+</button>
<button onClick={this.props.AppStore.decrement}>-</button>
</div>
)
}
}
export default App;
AppStore.js
import { observable, action } from "mobx";
class AppStore {
#observable counter = 0;
#action increment = () => {
this.counter = this.counter + 1;
console.log(this.counter);
}
#action decrement = () => {
this.counter = this.counter - 1;
console.log(this.counter);
}
}
const store = new AppStore();
export default store;
Since mobx#6.0.0 decorators are not enough. You have to make your class observable manually with makeObservable as well.
class AppStore {
#observable counter = 0;
constructor() {
makeObservable(this);
}
#action increment = () => {
this.counter = this.counter + 1;
}
#action decrement = () => {
this.counter = this.counter - 1;
}
}
Here I am trying to set innerHTML from my Test.js on render inside my componentDidMount. On the process I am getting errors of Unhandled Rejection (TypeError): Cannot set property 'innerHTML' of null .
I have gone through few questions where it defined to use refs() but unfotunately not able to use this in my case.
Any suggestion how can I use refs() here in my example?
demo Test.js
function updateList() {
const json = JSON.parse(localStorage["values"]);
if (json) {
picture = json.picture;
if (picture) {
userPicture = picture.name;
}
}
console.log(userPicture, "userPicture");
document.getElementById('picture').innerHTML = userPicture;
}
async function getAll () {
await updateList();
}
export default {
getAll
};
TestComponent.js
import React from 'react';
import Test from './Test';
class TestComponent extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
Test.getAll();
}
render() {
return (
<div className="test-item" >
<div className="test-picture" id="picture"> </div>
</div>
);
}
};
export default (injectIntl(TestComponent));
I believe this is what you want.
Code sandbox url - https://codesandbox.io/s/fervent-surf-n72h6?file=/src/index.js
App.component
import React from "react";
import { render } from "react-dom";
import Test from "./Test";
class App extends React.Component {
constructor(props) {
super(props);
this.divRef= React.createRef();
}
componentDidMount() {
Test.getAll(this.divRef);
}
render() {
return (
<div className="test-item">
<div className="test-picture" ref={this.divRef} id="picture">
Hello from component
</div>
</div>
);
}
}
const container = document.createElement("div");
document.body.appendChild(container);
render(<App />, container);
Test.js
function updateList(ref) {
ref.current.innerHTML = "Hello from Test.js";
}
async function getAll(ref) {
await updateList(ref);
}
export default {
getAll
};
I have two component in my project one is Tag and the other is LandingTicker so i want when i click Tag componet update state for LandTicker componet, and landticker componet in different file.
how i can do that?
thank you.
Tag component code::
tag/index.js
import React from 'react';
import './index.scss';
class Tag extends React.Component {
handleClick(e) {
let tags = document.querySelectorAll('.show-clickable');
Array.from(tags).map(el => el.classList.remove('selected-tag'))
e.target.classList.add('selected-tag');
/*
Here i should update the state for LandingTicker component.
and remember any component in different file.
How i can do that???
*/
}
render() {
return (
<div
className="show-clickable"
onClick={this.handleClick}
>
click here
</div>
);
}
}
export default Tag;
LandingTicker component code::
LandingTicker/index.js
import React from 'react';
import TickerRow from './TickerRow';
import './index.scss';
class LandingTicker extends React.Component {
state = {
coin: 'USD'
}
render() {
return (
<div className="landing-ticker__body">
{selectCoin(this.state.coin)}
</div>
</div>
);
}
}
const selectCoin = (coin) => {
const coins = {
USD: ['BTCUSD', 'ETHUSD', 'EOSUSD', 'LTCUSD'],
EUR: ['BTCEUR', 'ETHEUR', 'EOSEUR'],
GBP: ['BTCGBP', 'EOSGBP'],
JPY: ['BTCJPY', 'ETHJPY'],
};
return (
coins[coin].map(el =>
<TickerRow symbol={el} key={el.toString()} />
)
);
}
export default LandingTicker;
Edit:
my component Hierarchy::
StatusTable
TagsTable
Tag
TickerSearch
LandingTickers
TickersRow
StatusTable component code::
import React from 'react';
import TagsTable from './TagsTable';
import TickerSearch from './TickerSearch';
import LandingTicker from './LandingTicker';
import './StatusTable.scss';
class StatusTable extends React.Component {
render() {
return (
<div className="status-table">
<TagsTable />
<TickerSearch />
<LandingTicker />
</div>
);
}
}
export default StatusTable;
React handle all its component data in the form of state and props(immutable). So it is easy to pass data from parent to child or one component to another using props :
Your Tag.js file:
import React, { Component } from "react";
import LandingTicker from "./LandTicker";
class Tag extends Component {
constructor(props) {
super(props);
this.state = {
trigger: true
};
}
handleClick(e) {
// do all logic here and set state here
this.setState({ trigger: this.state.trigger });
}
render() {
//And then pass this state here as a props
return (
<div className="show-clickable" onClick={this.handleClick}>
click here
<LandingTicker trigger={this.state.trigger} />
</div>
);
}
}
export default Tag;
Inside LandTicker.js file:
import React from 'react';
import TickerRow from './TickerRow';
import './index.scss';
class LandingTicker extends React.Component {
state = {
coin: 'USD'
}
render() {
//Catch your props from parent here
//i.e this.props(it contains all data you sent from parent)
return (
<div className="landing-ticker__body">
{selectCoin(this.state.coin)}
</div>
);
}
}
const selectCoin = (coin) => {
const coins = {
USD: ['BTCUSD', 'ETHUSD', 'EOSUSD', 'LTCUSD'],
EUR: ['BTCEUR', 'ETHEUR', 'EOSEUR'],
GBP: ['BTCGBP', 'EOSGBP'],
JPY: ['BTCJPY', 'ETHJPY'],
};
return (
coins[coin].map(el =>
<TickerRow symbol={el} key={el.toString()} />
)
);
}
export default LandingTicker;
I think this is the best answer for your question if you don't use state management system such as Redux or Mobx.
https://medium.com/#ruthmpardee/passing-data-between-react-components-103ad82ebd17
(you need to check third option)
I'm using material-ui in a react app. Here's the code in question (I'll include the redux stuff just in case):
import React from 'react';
import { connect } from 'react-redux';
import { Button } from '#material-ui/core';
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<Button variant="contained" href="#constrained-buttons">
Link
</Button>
</div>
);
}
}
function mapStateToProps(state) {
const { alert } = state;
return {
alert
};
}
const connectedApp = connect(mapStateToProps)(App);
export { connectedApp as App };
I'm using https://material-ui.com/demos/buttons/ as a guide. Here's what shows up:
This is all that shows up. Any thoughts?