function how props in component - javascript

I have created a custom button component so that I don't have to always reuse them. but I have a problem and it is when executing a function.
The function is in the parent component, and what I want is to execute this function in the same parent component, but since I create a button component then I have to pass the function first to the button component and this is where I have the problem.
if I put func = {hello ()} the function is executed when entering the view, and if I put func = {hello} then clicking the button does nothing.
when I introduce the name of a route it works perfectly, the problem is when introducing a function of the parent component
CustomButtons.js
import React, { useState, useContext } from "react";
import { View } from 'react-native'
import { Button, Text } from 'react-native-elements';
import Icon from 'react-native-vector-icons/FontAwesome';
import { ThemeContext } from 'react-native-elements';
import { useNavigation } from '#react-navigation/native'
export default function CustomButtons(props) {
const { theme } = useContext(ThemeContext);
const navigation = useNavigation()
const themeButtons = {
btnClose: theme.colors.btnClose,
btnMain: theme.colors.btnMain,
btnAction: theme.colors.btnAction
}
const iconName = props.icon
const routeName = props.route
const actionFunc = props.func
const buttonName = props.name
const buttonType = props.type == 'icon' ? 'clear' : props.type == 'out' ? 'outline' : 'solid'
const iconColor = props.iconColor == null ? 'white' : props.iconColor
const buttonTheme = () => {
const theme = props.theme
if (theme == 'main') return themeButtons.btnMain
if (theme == 'close') return themeButtons.btnClose
if (theme == 'sec') return themeButtons.btnAction
}
const btnActionHandle = () => {
if (routeName) return navigation.navigate(routeName)
else {
return actionFunc
}
}
return (
<Button
title={buttonName}
icon={
<Icon
name={iconName}
color={iconColor}
size={15}
/>
}
buttonStyle={{ backgroundColor: buttonTheme() }}
onPress={btnActionHandle}
type={buttonType}
/>
);
}
parent component
.
.
.
function hello() {
console.log('Hello')
}
<CustomButtons
icon="trash"
type="icon"
iconColor="black"
func={hello}
/>
.
.
.
It should be noted that all the rest of the code works as expected except for the onPress = {} in the customButtons.js component

You forgot to execute/invoke/call it.
return actionFunc()
const btnActionHandle = () => {
if (routeName) return navigation.navigate(routeName)
else {
return actionFunc()
}
}
Also the same function can be re-written as below, no need for else block:
const btnActionHandle = () => {
if (routeName) {
return navigation.navigate(routeName)
}
return actionFunc()
}

Related

How to reparent Node in React

I want to change the parent of a Node in a way that
<div>
<children/>
</div>
becomes
<div>
<NewParent>
<children/>
</NewParent>
</div>
I need this to put a mui Tooltip above a component that overflows with ellipsis.
I implemented a small algorithm to find the needed element but when I try to use portals for this case this happens. enter image description here
My NewParent becomes the sibbling of the old parent.
Later I learned that usePortal brings the children to the parent and doesn't wrap the parent to the children so my question is what can I do to wrap a new parent to the node and make the old parent be the grandfather as per my first example
Current component
import React, { useRef, useEffect, useState } from 'react';
import { Tooltip } from '#mui/material';
import { Theme } from '#mui/material';
import { makeStyles } from '#mui/styles'
import { GridCellProps, GridCell } from '#mui/x-data-grid';
import { createPortal } from 'react-dom';
const useStyles = makeStyles<Theme>(() => ({
overflowEllipsis: {
width: '100%',
},
}))
const OverflowTip = React.forwardRef(({ children, ...props }: GridCellProps) => {
const [ portaled, setPortaled ] = useState(false)
const textElementRef = useRef<HTMLDivElement>();
const TooltipRef = useRef<HTMLDivElement>();
const classes = useStyles()
const compareSize = () => {
if (!textElementRef.current) {
return
}
const compare =
textElementRef.current.scrollWidth > textElementRef.current.clientWidth;
setHover(compare);
};
const findLowestChildren = (currentElement) => {
if (!currentElement) {
return
}
if (currentElement.children.length === 0) {
console.log(currentElement);
console.log(TooltipRef);
setPortaled(true)
createPortal(currentElement, TooltipRef.current)
currentElement.className += ` ${classes.overflowEllipsis}`
}
const arr = [].slice.call(currentElement.children);
return arr.forEach((ch) => {
if (ch.tagName === 'DIV' || ch.tagName === 'P' || ch.tagName === 'SPAN') {
return findLowestChildren(ch)
}
});
}
// compare once and add resize listener on "componentDidMount"
useEffect(() => {
compareSize();
window.addEventListener('resize', compareSize);
if (!portaled) {
findLowestChildren(textElementRef.current)
}
}, []);
// remove resize listener again on "componentWillUnmount"
useEffect(() => () => {
window.removeEventListener('resize', compareSize);
}, []);
// Define state and function to update the value
const [ hoverStatus, setHover ] = useState(false);
// console.log(props);
return (
<div ref={textElementRef}>
<GridCell
{...props}>
{children}
</GridCell>
<div ref={TooltipRef} className="wwwwwwww"><Tooltip title="QWEW"><></></Tooltip></div>
</div>
);
// return (
// <Tooltip
// title={children}
// disableHoverListener={!hoverStatus}
// >
// <BoxContainer
// ref={textElementRef}
// style={{
// whiteSpace: 'nowrap',
// overflow: 'hidden',
// textOverflow: 'ellipsis',
// }}>
// <GridCell
// {...props}
// >
// {children}
// </GridCell>
// </BoxContainer>
// </Tooltip>
// );
});
export default OverflowTip;

How to trigger a re-rendering of my Icon Component in React?

SOLUTION
Remove the style={{ fill: 'green' }} from the component and add this to the css file:
/*index.css*/
/* INFO: the sidebarleft-button contains a child that is an <svg> */
.sidebarleft-button-active > * {
fill: rgb(192, 192, 192);
}
.sidebarleft-button:hover > * {
fill: rgb(192, 192, 192);
}
PROBLEM(That is now solved)
I am working on a SideBar for my Application. The Sidebar contains Buttons. Each Button contains an Icon. I want to change the color of the icon if I hover with my mouse over the button. I tried many things and I wonder why no re-rendering is triggered because the icon changed and a change means re-rendering. I can see that the style.fill gets changed to blue in the inspector window of my browser.
I show you my code. The comments inside the code may help you.
//sideBarLeft.jsx
import React, { useState } from 'react';
import SideBarButton from './sideBarButton';
import { DIAGRAMTYPE } from '../diagramComponent/diagramUtils';
import { ReactComponent as BarChartIcon } from '../../icon/barChart.svg';
const SideBarLeft = (props) => {
const [btn0Active, setBtn0Active] = useState(true);
const [btn1Active, setBtn1Active] = useState(false);
const deactivateOtherButtonsAndActiveThisButton = (
idOfButtonThatWasClicked
) => {
switch (idOfButtonThatWasClicked) {
case 0:
setBtn1Active(false);
setBtn0Active(true);
break;
case 1:
setBtn0Active(false);
setBtn1Active(true);
break;
default:
setBtn0Active(false);
setBtn1Active(false);
}
};
return (
<div className={'sidebarleft'}>
<SideBarButton
active={btn0Active}
id={0}
deactivateOtherButtonsAndActiveThisButton={
deactivateOtherButtonsAndActiveThisButton
}
icon={<BarChartIcon style={{ fill: 'green' }} />}
diagramType={DIAGRAMTYPE.barChartPos}
/>
<SideBarButton
active={btn1Active}
id={1}
deactivateOtherButtonsAndActiveThisButton={
deactivateOtherButtonsAndActiveThisButton
}
icon={<BarChartIcon style={{ fill: 'green' }} />}
diagramType={DIAGRAMTYPE.barChartWordOccurence}
/>
</div>
);
};
export default SideBarLeft;
import React, { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actionCreators } from '../../state/index';
const SideBarButton = (props) => {
const dispatch = useDispatch();
const { switchToDiagramType } = bindActionCreators(actionCreators, dispatch);
const [cssClass, setCssClass] = useState('sidebarleft-button');
const onClickFn = () => {
props.deactivateOtherButtonsAndActiveThisButton(props.id);
switchToDiagramType(props.diagramType);
};
const [icon, setIcon] = useState(props.icon);
const buttonHandler = () => {};
const onMouseEnter = (component) => {
console.log('in onMouseEnter()');
const classOfComponent = component.target.classList.value;
if (classOfComponent === 'sidebarleft-button-active') {
console.log('component is active');
} else if (classOfComponent === 'sidebarleft-button') {
console.log('before');
console.log(props.icon); //even without mousenter, the component is already blue...
let changedIcon = props.icon;
props.icon.props.style.fill = 'blue';
setIcon(changedIcon); //in the inspector
//there is props->style->fill == 'blue'
//why does it not get rendered then in blue???
console.log('after');
console.log(changedIcon);
console.log('component is not active');
// console.log(component);
}
};
console.log('beforebefore');
console.log(icon);
return (
<button
onClick={onClickFn}
className={cssClass}
onMouseEnter={(component) => onMouseEnter(component)}
>
{icon}
</button>
);
};
export default SideBarButton;
Why not a css or sass approach?
.sidebarleft-button-active {
&:hover {
fill: blue;
}
}

ReactNative) Questions about calling a function that references data within the render()

The program flows as follows:
Home.js => Add.js => Detail.js => Repeat...
Home.js lists the posts.
Add.js is a page for entering the data required for a post. Move through stack navigation from Home.js
Detail.js will take over the data entered in Add.js as a parameter, show you the information of the post to be completed, and press the Done button to move to Home.js.
Home.js contains posts that have been completed.
If a post is created, eatObject is assigned an object from Detail.js.
Const { eatObject } = this.props.route?params || {};
In Home.js, state has an array of objects toEats.
Add eatObject to the object list
{Object.values(toEats).map(toEat =toEat.id toEat.idToEat key={toEat.id} {...toEat} deleteToEat={this._deleteToEat} />)}
Currently, the refresh button updates the 'Home.js' list whenever a post is added. But I want the list of posts to be updated automatically whenever 'Home.js' is uploaded.
I tried to call '_pushToEat' in 'componentDidMount', but 'eatObject' exists in 'render' so it seems impossible to hand it over to parameters.
I want to automatically call '_pushTooEat' when the components of 'Home.js' are uploaded.
Home.js
import React from "react";
import { View, Text, Button } from "react-native";
import ToEat from "./ToEat"
export default class Home extends React.Component {
state = {
toEats:{}
}
render() {
const { toEats } = this.state;
const { eatObject } = this.props.route?.params || {};
// error
// if (eatObject) {
// () => this._pushToEat(eatObject)
// }
return (
<View>
{Object.values(toEats).map(toEat => <ToEat key={toEat.id} {...toEat} deleteToEat={this._deleteToEat} />)}
<Button title="refresh" onPress={()=>this._pushToEat(eatObject)}/>
<View>
<Button title="Add" onPress={() => this.props.navigation.navigate("Add")} />
</View>
</View>
);
}
_deleteToEat = () => {
}
_pushToEat = (eatObject) => {
console.log("function call!")
console.log(eatObject)
this.setState(prevState => {
const newToEatObject = eatObject
const newState = {
...prevState,
toEats: {
...prevState.toEats,
...newToEatObject
}
}
return { ...newState };
})
}
}
Detail.js
import React from "react";
import { View, Text, Button } from "react-native";
import uuid from 'react-uuid'
import { connect } from 'react-redux';
import { inputId } from '../src/reducers/infoReducer';
class Detail extends React.Component {
render() {
const { name, dosage, note } = this.props.route.params;
return (
<View>
<Text>name: {name}</Text>
<Text>dosage: {dosage}</Text>
<Text>note: {note}</Text>
<Button
title="Done"
onPress={() =>
this.props.navigation.navigate(
"Home", {
eatObject: this._createToEat(uuid(), name, dosage)
})
}
/>
</View>
)
}
_createToEat = (id, name, dosage) => {
const ID = id
inputId(id)
const newToEatObject = {
[ID]: {
id: ID,
name: name,
dosage: dosage,
}
}
return newToEatObject;
}
}
function mapStateToProps(state) {
return {
state: state.infoReducer
};
}
function matchDispatchToProps(dispatch) {
return {
inputId: (id) => {
dispatch(inputId(id));
},
}
}
export default connect(mapStateToProps, matchDispatchToProps)(Detail);
I want your advice.
Thank you

Show the last index in an array when I click (in an array that continues to be updated)

I am near the end of creating my application.
So it is for banks accounts where they ask you to give the first letter of your password, then for example fourth, etc.
I'm tired of counting on my own so I created this app.
But there is the last bug that I don't know how to fix.
So when I press "1" I get "1 - H", and then when I press "4" I want to get:
"1 - H" (clicked before)
"4 - X" (clicked just now)
but instead, I get:
"4 - X" (clicked just now)
"4 - X" (clicked just now)
So it is caused by the way handleResults() function works inside my Input component, but for now it is my only concept how to approach this...
import React, { Component } from 'react';
import TextField from 'material-ui/TextField';
import './style.css';
import Buttons from '../Buttons';
import Results from '../Results';
class Input extends Component {
constructor(props) {
super(props);
this.state = {
password: 'Hh9Xzke2ayzcEUPHuIfS',
selectedButtons: [],
};
this.handleButtonSelectTwo = this.handleButtonSelectTwo.bind(this);
}
handleInputChange(pass) {
this.setState({ password: pass });
}
handleButtonSelectTwo(selected) {
this.setState({
selectedButtons: [...this.state.selectedButtons, selected],
});
}
handleResults() {
return this.state.selectedButtons.map(el => (
<Results key={el} appState={this.state} />
));
}
render() {
return (
<div>
<div className="Input-textfield">
<TextField
hintText="Paste your password here to begin"
value={this.state.password}
onChange={event => this.handleInputChange(event.target.value)}
/>
</div>
<div>
<Buttons
handleButtonSelectOne={this.handleButtonSelectTwo}
array={this.state.password.length}
/>
{this.handleResults()}
</div>
</div>
);
}
}
export default Input;
and here is Results component code:
import React, { Component } from 'react';
import _ from 'lodash';
import Avatar from 'material-ui/Avatar';
import List from 'material-ui/List/List';
import ListItem from 'material-ui/List/ListItem';
import './style.css';
const style = {
avatarList: {
position: 'relative',
left: -40,
},
avatarSecond: {
position: 'relative',
top: -40,
left: 40,
},
};
class Results extends Component {
resultsEngine(arg) {
const { selectedButtons, password } = this.props.appState;
const passwordArray = password.split('').map(el => el);
const lastSelectedButton = _.last(selectedButtons);
const passwordString = passwordArray[_.last(selectedButtons) - 1];
if (arg === 0) {
return lastSelectedButton;
}
if (arg === 1) {
return passwordString;
}
return null;
}
render() {
if (this.props.appState.selectedButtons.length > 0) {
return (
<div className="test">
<List style={style.avatarList}>
<ListItem
disabled
leftAvatar={<Avatar>{this.resultsEngine(0)}</Avatar>}
/>
<ListItem
style={style.avatarSecond}
disabled
leftAvatar={<Avatar>{this.resultsEngine(1)}</Avatar>}
/>
</List>
</div>
);
}
return <div />;
}
}
export default Results;
Anyone has an idea how should I change my code inside handleResults() function to achieve my goal? Any help with solving that problem will be much appreciated.
Buttons component code:
import React from 'react';
import OneButton from '../OneButton';
const Buttons = props => {
const arrayFromInput = props.array;
const buttonsArray = [];
for (let i = 1; i <= arrayFromInput; i++) {
buttonsArray.push(i);
}
const handleButtonSelectZero = props.handleButtonSelectOne;
const allButtons = buttonsArray.map(el => (
<OneButton key={el} el={el} onClick={handleButtonSelectZero} />
));
if (arrayFromInput > 0) {
return <div>{allButtons}</div>;
}
return <div />;
};
export default Buttons;
And OneButton code:
import React, { Component } from 'react';
import RaisedButton from 'material-ui/RaisedButton';
const style = {
button: {
margin: 2,
padding: 0,
minWidth: 1,
},
};
class OneButton extends Component {
constructor() {
super();
this.state = { disabled: false };
}
handleClick() {
this.setState({ disabled: !this.state.disabled });
this.props.onClick(this.props.el);
}
render() {
return (
<RaisedButton
disabled={this.state.disabled}
key={this.props.el}
label={this.props.el}
style={style.button}
onClick={() => this.handleClick()}
/>
);
}
}
export default OneButton;
In your resultsEngine function in the Results component you are specifying that you always want the _.last(selectedButtons) to be used. This is what it is doing, hence you always see the last button clicked. What you actually want is the index of that iteration to show.
const lastSelectedButton = selectedButtons[this.props.index];
const passwordString = passwordArray[selectedButtons[this.props.index]];
To get an index you have to create and pass one in, so create it when you map over the selected Buttons in the handleResults function in your Input component.
handleResults() {
return this.state.selectedButtons.map((el, index) => (
<Results key={el} appState={this.state} index={index} />
));
}

React function getting called on every change

I am building an isomorphic React app. The workflow I am currently working through is :
User navigates to the /questions route which makes the API call server side and loads the data on the page. This calls the renderData() function like it should and loads all the questions for the user to see.
User clicks add button to add new question and a modal pops up for a user to enter in the form fields and create a new question.
With every change in the modal, the renderData() function is getting called (which it shouldn't). When the user clicks the Create Question button, the renderData() function is also getting called is throwing an error because the state changes.
I can't pinpoint why the renderData() function is getting called every single time anything happens in the modal. Any ideas as to why this is happening and how to avoid it?
Main component :
import React, { Component, PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './QuestionsPage.scss';
import QuestionStore from '../../stores/QuestionStore';
import QuestionActions from '../../actions/QuestionActions';
import Loader from 'react-loader';
import QuestionItem from '../../components/QuestionsPage/QuestionItem';
import FloatButton from '../../components/UI/FloatButton';
import AddQuestionModal from '../../components/QuestionsPage/AddQuestionModal';
const title = 'Questions';
class QuestionsPage extends Component {
constructor(props) {
super(props);
this.state = QuestionStore.getState();
this.onChange = this.onChange.bind(this);
this.openModal = this.openModal.bind(this);
this.closeMOdal = this.closeModal.bind(this);
}
static contextTypes = {
onSetTitle: PropTypes.func.isRequired,
};
componentWillMount() {
this.context.onSetTitle(title);
QuestionStore.listen(this.onChange);
}
componentWillUnmount() {
QuestionStore.unlisten(this.onChange);
}
onChange(state) {
this.setState(state);
}
openModal = () => {
this.setState({ modalIsOpen: true});
}
closeModal = () => {
this.setState({ modalIsOpen: false});
}
createQuestion = () => {
const date = new Date();
const q = this.state.question;
q.createdAt = date;
this.setState({ question : q });
QuestionStore.createQuestion(this.state.question);
}
textChange = (val) => {
const q = this.state.question;
q.text = val;
this.setState({ question : q });
}
answerChange = (val) => {
const q = this.state.question;
q.answer = val;
this.setState({ question : q });
}
tagChange = (val) => {
const q = this.state.question;
q.tag = val;
this.setState({ question : q });
}
companyChange = (val) => {
const q = this.state.question;
q.company = val;
this.setState({ question : q });
}
renderData() {
return this.state.data.map((data) => {
return (
<QuestionItem key={data.id} data={data} />
)
})
}
render() {
return (
<div className={s.root}>
<div className={s.container}>
<h1>{title}</h1>
<div>
<Loader loaded={this.state.loaded} />
<FloatButton openModal={this.openModal}/>
<AddQuestionModal
open = {this.state.modalIsOpen}
close = {this.closeModal}
createQuestion = {this.createQuestion}
changeText = {this.textChange}
changeAnswer = {this.answerChange}
changeTag = {this.tagChange}
changeCompany = {this.companyChange}
/>
{ this.renderData() }
</div>
</div>
</div>
);
}
}
export default withStyles(QuestionsPage, s);
Modal Component :
import React, { Component, PropTypes } from 'react';
import QuestionStore from '../../stores/QuestionStore';
import QuestionActions from '../../actions/QuestionActions';
import Modal from 'react-modal';
import TextInput from '../UI/TextInput';
import Button from '../UI/Button';
class AddQuestionModal extends Component {
createQuestion = () => {
this.props.createQuestion();
}
closeModal = () => {
this.props.close();
}
changeText = (val) => {
this.props.changeText(val);
}
changeAnswer = (val) => {
this.props.changeAnswer(val);
}
changeTag = (val) => {
this.props.changeTag(val);
}
changeCompany = (val) => {
this.props.changeCompany(val);
}
render() {
return (
<Modal
isOpen={this.props.open}
onRequestClose={this.closeModal} >
<TextInput
hintText="Question"
change={this.changeText} />
<TextInput
hintText="Answer"
change={this.changeAnswer} />
<TextInput
hintText="Tag"
change={this.changeTag} />
<TextInput
hintText="Company"
change={this.changeCompany} />
<Button label="Create Question" onSubmit={this.createQuestion} disabled={false}/>
<Button label="Cancel" onSubmit={this.closeModal} disabled={false}/>
</Modal>
);
}
}
export default AddQuestionModal;
On click of
It's happening because every change causes you to call the setState method and change the state of the main component. React will call the render function for a component every time it detects its state changing.
The onChange event on your inputs are bound to methods on your main component
Each method calls setState
This triggers a call to render
This triggers a call to renderData
React allows you to change this by overriding a shouldComponentUpdate function. By default, this function always returns true, which will cause the render method to be called. You can change it so that only certain changes to the state trigger a redirect by comparing the new state with the old state.

Categories