Builder Action positionRComponent not called. Am I doing something wrong? Check out the commentLine inside moveBox function in the BuildView.js
Expecting output: to be printed in console.
Position R Component
Below are the code snippets of BuildView.js and builder-actions.js.
BuildView.js
import React, {PropTypes} from 'react';
import BuilderStore from '../stores/builder-store';
import BuilderActions from '../actions/builder-actions'
import update from 'react/lib/update';
import ItemTypes from './ItemTypes';
import RComponent from './RComponent';
import { DropTarget } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
function getViewRComponents(){
return( {components: BuilderStore.getViewRComponents()})
}
const rComponentTarget = {
drop(props, monitor, component) {
const item = monitor.getItem();
const delta = monitor.getDifferenceFromInitialOffset();
const left = Math.round(item.left + delta.x);
const top = Math.round(item.top + delta.y);
component.moveBox(item.id, left, top);
}
};
const wrapper = {
border: '1px solid grey'
}
function collect(connect, monitor){
return ({
connectDropTarget: connect.dropTarget()
})
}
class BuildView extends React.Component{
constructor(props){
super(props);
this.state = getViewRComponents();
this._onChange = this._onChange.bind(this);
}
moveBox(id, left, top) {
this.setState(update(this.state, {
components: {
[id]: {
$merge: {
left: left,
top: top
}
}
}
}));
//CALLING HERE>>> Not getting called
BuilderActions.positionRComponent.bind(null, this.state.components[id]);
}
componentWillMount(){
BuilderStore.addChangeListener(this._onChange)
}
render(){
const { hideComponentOnDrag, connectDropTarget } = this.props;
let components = this.state.components.map( (component, index) => {
return(<RComponent
key={index}
id={index}
left={component.left}
top={component.top}
hideComponentOnDrag={hideComponentOnDrag}>
{component.name}
</RComponent>);
})
return connectDropTarget(
<div>
{components}
</div>
);
}
_onChange(){
this.setState(getViewRComponents());
}
componentWillUnMount(){
BuilderStore.removeChangeListener(this._onChange())
}
}
BuildView.propTypes = {
hideComponentOnDrag: PropTypes.bool.isRequired,
connectDropTarget: PropTypes.func.isRequired
};
export default DropTarget(ItemTypes.RCOMPONENT,rComponentTarget, collect )(BuildView);
builder-actions.js
import BuilderConstants from '../constants/builder-constants';
import {dispatch, register} from '../dispatchers/builder-dispatcher';
export default {
addRComponent(component) {
console.log("Add R Component")
dispatch({
actionType: BuilderConstants.ADD_RCOMPONENT, component
})
},
removeRComponent(component){
dispatch({
actionType: BuilderConstants.REMOVE_RCOMPONENT, component
})
},
positionRComponent(component){
console.log("Position R Component");
dispatch({
actionType: BuilderConstants.POSITION_RCOMPONENT, component
})
}
}
Use call or execute the returned function from bind:
var f = BuilderActions.positionRComponent.bind(null, this.state.components[id])
f()
or:
BuilderActions.positionRComponent.call(null, this.state.components[id]);
The difference is bind doesn't execute but returns a new function with the argument list passed into the new function.
call basically does a bind then executes, apply is similar but takes an array of arguments.
Hope it helps.
Related
I'm using reactjs with redux for state management. I want to change state in a component with redux. but when I send props to the component and I inspect it with console.log(), returned undefined to me.
please guide me to solve problem...
thanks
Svg Viewer Component
import React, { useEffect, useState, useContext } from "react";
import * as d3 from "d3";
import store from "../../redux/store";
const SvgViewer = ({ nodesData, svgFilePath, props }) => {
//const { visible, invisible } = props;
const [svgContainer, setSvgContainer] = useState(undefined);
const showNodesOnSvg = nodes => {
let svgDoc = svgContainer.contentDocument;
let gTags = svgDoc.querySelectorAll("svg > g");
let container = null;
if (gTags.length > 1) container = svgDoc.querySelector("g:nth-of-type(2)");
else container = svgDoc.querySelector("g:nth-of-type(1)");
let node = d3.select(container);
nodesData.forEach(nodeData => {
node
.append("text")
.attr("id", "node" + nodeData["id"])
.attr("fill", "white")
.attr("text-anchor", "middle")
.attr("x", nodeData["positionX"])
.attr("y", nodeData["positionY"])
.attr("class", "clickable-node")
.style("font-size", "8px")
.style("position", "absolute")
.style("cursor", "pointer")
.style("display", "inline-block")
.on("click", function() {
clickHandler(nodeData["id"]);
})
.text("N/A" + " " + nodeData["symbol"]);
let nodeCreated = d3.select(
svgDoc.getElementById("node" + nodeData["id"])
);
nodeCreated
.append("title")
.attr("id", "title" + nodeData["id"])
.text(" " + nodeData["tagCode"]);
});
};
const clickHandler = nodeID => {
console.log(props); //not show props
};
useEffect(() => {
const svg = document.querySelector("#svgobject");
setSvgContainer(svg);
svg.onload = () => {
if (nodesData != null) {
showNodesOnSvg();
}
};
});
return (
<div className="unit-schema-container1" key={svgFilePath}>
{/* <Spin indicator={objectLoading} spinning={this.state.objectLoading}> */}
<object id="svgobject" type="image/svg+xml" data={svgFilePath}></object>
{/* </Spin> */}
</div>
);
};
export default SvgViewer;
store
import { createStore, combineReducers } from "redux";
import modalReducer from "./reducers/modalReducer";
const store = createStore(modalReducer);
export default store;
Reducer:
function modalReducer(state = initialState, action) {
const initialState = false;
switch (action.type) {
case "VISIBALE":
return (state = true);
case "INVISIBALE":
return (state = false);
default:
return state;
}
}
export default modalReducer;
Action
export function visible() {
return {
type: "VISIBLE"
};
}
export function invisible() {
return {
type: "INVISIBLE"
};
}
Svg Container
import { visible, invisible } from "../redux/actions/modalAction";
import { connect } from "react-redux";
import svgViewer from "../pages/unit-monitor/svg-viewer";
const mapStateToProps = state => ({
visibale: state.value
});
const mapDispatchToProps = dispatch => {
return {
visible: () => dispatch(visible()),
invisible: () => dispatch(invisible())
};
};
export default connect(mapStateToProps, mapDispatchToProps)(svgViewer);
Svg Component
import React, { PureComponent } from "react";
import { Row, Col, Spin, Icon } from "antd";
import axios from "axios";
import "./tree-select.scss";
import History from "./history";
import SchemaTreeSelect from "./schema-tree-select";
import SvgViewer from "../../container/svgViewerContainer";
class UnitMonitor extends PureComponent {
constructor() {
super();
}
state = {
nodes: undefined,
nodeId: 25,
valueSignalR: [],
searchText: "",
selectedChart: "Line",
tsSchemaLoading: false,
objectLoading: false,
svgFilePath: ""
};
onChangeShcema = schemaID => {
axios.get("/api/schemata/get-schemata-nodes/" + schemaID).then(response => {
this.setState({ nodes: response.data });
let path = response.data[0].file;
let svgFile = require("./images/" + path);
this.setState({ svgFilePath: svgFile });
});
};
render() {
return (
<Row type="flex" className="">
<Col span={25}>
<SchemaTreeSelect handleChange={this.onChangeShcema} />
<History nodeId={this.state.nodeId} />
<SvgViewer
svgFilePath={this.state.svgFilePath}
nodesData={this.state.nodes}
/>
</Col>
</Row>
);
}
}
export default UnitMonitor;
You are trying to read the value property on state, but there is no such property on the state returned by your reducer... it is just true or false so replace the state.value with the state itself in your mapStateToProps.
const mapStateToProps = state => ({
visibale: state
});
Also there is an inconsistency between your types used for dispatching the actions on the redux state.
"VISIBALE"/ "UNVISIBALE" is used in reducer while "VISIBLE"/ "INVISIBLE" is used in action dispatcher.`
Trying to test this component, and im getting this
error
TypeError: this.props.onItemAdded is not a function
I've referenced this but this solution doesn't really apply to my problem
Enzyme test: TypeError: expect(...).find is not a function
How would i test the button functionality being that the button is a prop ?
todo-add-item.test.js
import React from "react";
import { shallow } from "enzyme";
import TodoAddItem from './todo-add-item';
describe('Should render add item component', ()=> {
it('should render add item component', () => {
const wrapper = shallow(<TodoAddItem/>)
})
})
describe('Should simulate button click', ()=> {
it('should simulate button click', () => {
const wrapper =shallow(<TodoAddItem/>)
wrapper.find('button').simulate('click') // getting the type error here.
})
})
todo-add-item.js
import React, { Component } from 'react';
import './todo-add-item.css';
export default class TodoAddItem extends Component {
render() {
return (
<div className="todo-add-item">
<button
className="test-button btn btn-outline-secondary float-left"
onClick={() => this.props.onItemAdded('Hello world')}>
Add Item
</button>
</div>
);
}
}
app.js
import React, { Component } from 'react';
import AppHeader from '../app-header';
import SearchPanel from '../search-panel';
import TodoList from '../todo-list';
import ItemStatusFilter from '../item-status-filter';
import TodoAddItem from '../todo-add-item';
import './app.css';
export default class App extends Component {
constructor() {
super();
this.createTodoItem = (label) => {
return {
label,
important: false,
done: false,
id: this.maxId++
}
};
this.maxId = 100;
this.state = {
todoData: [
this.createTodoItem('Drink Coffee'),
this.createTodoItem('Make Awesome App'),
this.createTodoItem('Have a lunch')
]
};
this.deleteItem = (id) => {
this.setState(({ todoData }) => {
const idx = todoData.findIndex((el) => el.id === id);
const newArray = [
...todoData.slice(0, idx),
...todoData.slice(idx + 1)
];
return {
todoData: newArray
};
});
};
this.addItem = (text) => {
const newItem = this.createTodoItem(text);
this.setState(({ todoData }) => {
const newArray = [
...todoData,
newItem
];
return {
todoData: newArray
};
});
};
this.onToggleImportant = (id) => {
console.log('toggle important', id);
};
this.onToggleDone = (id) => {
console.log('toggle done', id);
};
};
render() {
return (
<div className="todo-app">
<AppHeader toDo={ 1 } done={ 3 } />
<div className="top-panel d-flex">
<SearchPanel />
<ItemStatusFilter />
</div>
<TodoList
todos={ this.state.todoData }
onDeleted={ this.deleteItem }
onToggleImportant={ this.onToggleImportant }
onToggleDone={ this.onToggleDone } />
<TodoAddItem onItemAdded={ this.addItem } />
</div>
);
};
};
You don't pass any props to your component.
const wrapper =shallow(<TodoAddItem onItemAdded={() => jest.fn()}/>)
You can check props with .props()
Eg:
console.log('props',wrapper.find('button').props());
How to make counter of renders the child component in parent?
I have 2 components Widget (parent) and Message(child). I passed counter from child to parent and trying to set getting value from child set to state. And I getting err: Maximum update depth exceeded.
There is child component Message:
import React, { Component } from "react";
export default class Message extends React.Component {
constructor(props) {
super(props);
this.changeColor = this.changeColor.bind(this);
this.changeCount = this.changeCount.bind(this);
this.state = { h: 0, counter: 0 };
}
changeColor = () => {
this.setState(state => ({
h: Math.random()
}));
};
changeCount = () => {
this.setState(state => ({
counter: ++state.counter
}));
};
componentDidUpdate(prevProps) {
this.props.getColor(this.color);
this.changeCount();
this.props.getCount(this.state.counter);
}
render() {
const { children } = this.props;
const { s, l, a } = this.props.color;
this.color = `hsla(${this.state.h}, ${s}%, ${l}%, ${a})`;
return (
<p
className="Message"
onClick={this.changeColor}
style={{ color: this.color }}
>
{children}
</p>
);
}
}
There is parent component:
import React, { Component } from "react";
import Message from "./Message/Message";
export default class Widget extends React.Component {
constructor(props) {
super(props);
this.state = {
color: {
s: 30,
l: 60,
a: 1
},
counter: 0
};
}
getCount = count => this.setState(state => ({
counter: state.counter
}));
getColor = color => {
console.log(`the color is ${color}`);
};
render() {
const counter = this.state.counter;
return (
<div>
<Message
getColor={this.getColor}
getCount={this.getCount}
color={this.state.color}
>
{undefined || `Hello World!`}
</Message>
{counter}
</div>
);
}
}
What I do wrong?
The answer by #Yossi counts total renders of all component instances. This solution counts how many renderes and re-renders an individual component has done.
For counting component instance renders
import { useRef } from "react";
export const Counter = props => {
const renderCounter = useRef(0);
renderCounter.current = renderCounter.current + 1;
return <h1>Renders: {renderCounter.current}, {props.message}</h1>;
};
export default class Message extends React.Component {
constructor() {
this.counter = 0;
}
render() {
this.counter++;
........
}
}
In order to count the number of renders, I am adding a static variable to all my components, and incrementing it within render().
For Class components:
import React, { Component } from 'react';
import { View, Text } from 'react-native';
let renderCount = 0;
export class SampleClass extends Component {
render() {
if (__DEV__) {
renderCount += 1;
console.log(`${this.constructor.name}. renderCount: `, renderCount);
}
return (
<View>
<Text>bla</Text>
</View>
)
}
}
For functional Components:
import React from 'react';
import { View, Text } from 'react-native';
let renderCount = 0;
export function SampleFunctional() {
if (__DEV__) {
renderCount += 1;
console.log(`${SampleFunctional.name}. renderCount: `, renderCount);
}
return (
<View>
<Text>bla</Text>
</View>
)
}
The componentDidUpdate is calling this.changeCount() which calls this.setState() everytime after the component updated, which ofcourse runs infinitely and throws the error.
componentDidUpdate(prevProps) {
this.props.getColor(this.color);
// Add a if-clause here if you really want to call `this.changeCount()` here
// For example: (I used Lodash here to compare, you might need to import it)
if (!_.isEqual(prevProps.color, this.props.color) {
this.changeCount();
}
this.props.getCount(this.state.counter);
}
import { Mongo } from 'meteor/mongo';
import { Meteor } from 'meteor/meteor';
import React, {Component} from 'react';
import {check} from 'meteor/check';
export const Adressen = new Mongo.Collection('Phonebook');
if (Meteor.isServer) {
Meteor.publish('ArrayToExport', function(branches) {
check(branches, [Match.Any]);
if(branches.length > 10){
return this.ready()
};
return Adressen.find(
{branche: {$in: branches}}, {fields: {firmenname:1, plz:1}}
);
});
}
.
import React, { Component } from 'react';
import { withTracker } from 'meteor/react-meteor-data';
import {Adressen} from "../api/MongoDB";
class ExportArray extends Component{
constructor(props){
super(props);
this.state = {
branches: this.props.filteredBranches
};
}
render(){
return(
<div>
<button onClick={this.exportArrays}></button>+
</div>
);
}
}
export default withTracker( (branches) => {
Meteor.subscribe('ArrayToExport', branches);
return {
ArrayToExport: Adressen.find({}).fetch()
};
})(ExportArray);
this.props.filteredBranche is a pure array,generated through controlled input field. this.props.filteredBranches changes as Input changes, in parent Component.
I thought I was sending my this.props.filteredBranches as an argument through withTracker function. But nothing is passed to the publish function.
if (Meteor.isServer) {
arrayExfct = function (array){
return {
find: {branche:{$in: array }},
fields: {firmenname:1, plz:1}
};
}
Meteor.publish('ArrayToExport', function (array) {
return Adressen.find(
arrayExfct(array).find, arrayExfct(array).fields);
});
}
.
export default withTracker( () => {
arrayExfct = function(array) {
return {
find: {branche: {$in: array}},
fields: {firmenname:1, plz:1}
}
}
var array = ['10555'];
Meteor.subscribe('ArrayToExport', array );
var arrayExfct = Adressen.find(arrayExfct(array).find, arrayExfct(array).fields);
return {
ArrayToExport: Adressen.find({}).fetch()
};
})(ExportArray);
It would help if you also added an example of where you used this component and how you pass props to it, but I think I see your problem.
You expect the local state in your rendering component to get into the withTracker container, but that would be the other way around. When you make the withTracker container, you are really making another react component that renders your display component (ExportArray) and passes the data (ArrayToExport) down into it.
So, props go like this currently:
external render -> withTracker component -> ExportArray
What you need to do it to get the filteredBranches (which you pass from a parent component?) from the props argument in withTracker and pass that to the subscribtion,
class ExportArray extends Component{
exportArrays () {
const { ArrayToExport } = this.props;
}
render(){
const { ArrayToExport } = this.props;
return(
<div>
<button onClick={this.exportArrays}></button>+
</div>
);
}
}
export default withTracker(propsFromParent => {
const { filteredBranches } = propsFromParent;
Meteor.subscribe('ArrayToExport', filteredBranches);
return {
ArrayToExport: Adressen.find({}).fetch()
};
})(ExportArray);
Hi the issue is with the code below. The parameter called branches is the props so branches.branches is the array you passed in.
export default withTracker( (branches) => {
Meteor.subscribe('ArrayToExport', branches);
return {
ArrayToExport: Adressen.find({}).fetch()
};
})(ExportArray);
Try the following.
export default withTracker( ({branches}) => {
Meteor.subscribe('ArrayToExport', branches);
return {
ArrayToExport: Adressen.find({}).fetch()
};
})(ExportArray);
Notice all that changed was
(branches)
became
({branches})
I solved my problem with a combination of Session Variables and State.
//Client
import React, { Component } from 'react';
import { withTracker } from 'meteor/react-meteor-data';
import {Adressen} from "../api/MongoDB";
import {Meteor} from 'meteor/meteor';
import { Session } from 'meteor/session';
class ExportArray extends Component{
constructor(){
super();
this.state = {
x: [],
y: []
};
this.exportArrays = this.exportArrays.bind(this);
}
exportArrays(e){
e.preventDefault();
this.setState({x: this.props.filteredBranches});
this.setState({y: this.props.filteredPostleitzahlen});
}
render(){
var selector = {branche: {$in: this.state.x},plz: {$in: this.state.y}};
Session.set('selector', selector);
return(
<div>
<button onClick={this.exportArrays}> Commit </button>
</div>
);
}
}
export default withTracker( () => {
const ArrayfürExport = Meteor.subscribe('ArrayToExport', Session.get('selector') );
return {
ArrayToExport: Adressen.find({}).fetch()
};
})(ExportArray);
//Server
Meteor.publish('ArrayToExport', function (selector) {
console.log('von mongodb', selector);
return Adressen.find(
selector
, {
fields: {firmenname:1, plz:1}
});
});
}
I'm pretty new to React and Redux and very new to react-dnd, and I think I'm doing something wildly incorrect here. Although there are other similar posts out there I can't quite find a solution in them.
I'm working on a Kanban board app that is somewhat based on the one found at https://survivejs.com/react/implementing-kanban/drag-and-drop/ though that version uses Alt.js and I'm using Redux.
The problem: when dragging a component, the action function is called but the case in the reducer (MOVE_TICKET) is not. This seems to be the case regardless of the content of the action function.
I linked the action to a click event and in this instance the action and reducer worked as expected. This leads me to think that it must be a problem with the way I've set up the Ticket component with the dnd functions.
Ticket.js:
import React from "react"
import {compose} from 'redux';
import { DragSource, DropTarget } from 'react-dnd';
import ItemTypes from '../constants/ItemTypes';
import { moveTicket } from "../actions/ticketsActions"
const Ticket = ({
connectDragSource, connectDropTarget, isDragging, isOver, onMove, id, children, ...props
}) => {
return compose (connectDragSource, connectDropTarget)(
<div style={{
opacity: isDragging || isOver ? 0 : 1
}} { ...props } className = 'ticket'>
<h3 className = 'summary'> { props.summary } </h3>
<span className = 'projectName'> { props.projectName }</span>
<span className = 'assignee'> { props.assignee } </span>
<span className = 'priority'> { props.priority } </span>
</div>
);
};
const ticketSource = {
beginDrag(props) {
return {
id: props.id,
status: props.status
};
}
};
const ticketTarget = {
hover(targetProps, monitor) {
const targetId = targetProps.id;
const sourceProps = monitor.getItem();
const sourceId = sourceProps.id;
const sourceCol = sourceProps.status;
const targetCol = targetProps.status;
if(sourceId !== targetId) {
targetProps.onMove({sourceId, targetId, sourceCol, targetCol});
}
}
};
export default compose(
DragSource(ItemTypes.TICKET, ticketSource, (connect, monitor) => ({
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
})),
DropTarget(ItemTypes.TICKET, ticketTarget, (connect, monitor) => ({
connectDropTarget: connect.dropTarget(),
isOver: monitor.isOver()
}))
)(Ticket)
ticketsReducer.js:
export default function reducer(state={
tickets: [],
fetching: false,
fetched: false,
error: null,
}, action) {
switch (action.type) {
case "MOVE_TICKET": {
return [{...state, tickets: action.payload}]
}
}
return state
}
ticketsActions.js
import store from '../store';
export function moveTicket({sourceId, targetId, sourceCol, targetCol}) {
const columns = Object.assign({}, store.getState().tickets.tickets)
const sourceList = columns[sourceCol];
const targetList = columns[targetCol];
const sourceTicketIndex = sourceList.findIndex(ticket => ticket.id == sourceId);
const targetTicketIndex = targetList.findIndex(ticket => ticket.id == targetId);
if(sourceCol === targetCol){
var arrayClone = sourceList.slice();
arrayClone.splice(sourceTicketIndex, 1);
arrayClone.splice(targetTicketIndex, 0, sourceList[sourceTicketIndex]);
columns[sourceCol] = arrayClone;
}
return function(dispatch){
dispatch({type: "MOVE_TICKET", payload: columns});
}
}
Column.js (where each Ticket component is rendered)
import React from "react"
import uuid from "uuid"
import { connect } from "react-redux"
import ColumnsContainer from "./ColumnsContainer"
import Ticket from "./ticket"
import { moveTicket } from "../actions/ticketsActions"
#connect((store) => {
return {
columns: store.columns.columns
};
})
export default class Column extends React.Component {
console(){
console.log(this)
}
render(){
const tickets = this.props.tickets.map((ticket, id) =>
<Ticket
key = {uuid.v4()}
id={ticket.id}
summary = { ticket.summary }
assignee = { ticket.assignee }
priority = { ticket.priority }
projectName = { ticket.displayName }
onMove={ moveTicket }
status= { ticket.status }
/>
)
return(
<div key = {uuid.v4()} className = { this.props.className }>
<h2 key = {uuid.v4()}>{ this.props.title }</h2>
<ul key = {uuid.v4()}>{ tickets }</ul>
</div>
)
}
}
If anyone can see where I'm going wrong I could really use some assistance.
You are not connecting the moveTicket action to redux's dispatcher.
You'll have to do something like:
#connect((store) => {
return {
columns: store.columns.columns
};
}, {moveTicket})
export default class Column extends React.Component {
// ...
// use this.props.moveTicket instead of moveTicket
The second parameter to connect is called mapDispatchToProps, which will do the dispatch(actionFn) for you.
You might want to name the bound action differently, e.g.
#connect((store) => {
return {
columns: store.columns.columns
};
}, {connectedMoveTicket: moveTicket})
// then use this.props.connectedMoveTicket