Mount React Portal somewhere the current rendering component - javascript

I'm trying to mount a React Portal whose node is the member of current rendering component. As per shown in the below code, I've to forcefully re-render it by setting a state in the componentDidMount which seems to be an anti-pattern to me.
import React from 'react';
import PropTypes from 'prop-types';
import FormProduct from 'containers/FormProduct';
import Portal from 'shared/Portal';
class Users extends React.Component {
constructor(props) {
super(props);
this.productForm = React.createRef();
this.state = {
mounted: false,
}
}
componentDidMount() {
this.setState({ mounted: true});
}
render() {
return (
<React.Fragment>
<div className="mt-20" ref={this.productForm}></div>
{this.state.mounted && <Portal node={this.productForm.current}>
<FormProduct />
</Portal>}
</React.Fragment>
)
}
}
How can we achieve it in the first rendering?

Related

why my HOC Component is working properly ? #React

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

Delete button - change state with handleClick

I am currently trying to write the code for my handleClick() function in my CARD.js file.
I am trying to delete the card when the delete button gets clicked. I am struggling with this because the state that needs to be changed is in my HOME file and not in the CARD file where my handleclick function is. What code should I use in my handleclick function (CARD file) to filter (=delete) the state in the HOME file? How do you do this linking or is it not possible?
HOME.js
import React, { PureComponent } from 'react'
import {movies} from "./movies.js"
import Card from "./Card.js"
import "./Home.css"
class Home extends PureComponent {
constructor(props) {
super(props)
this.state = {
movieslist: movies
}
}
render() {
return (
<div className="homecontainer">
{
this.state.movieslist.map(movie =>{
return <Card title={movie.title} category={movie.category} likes={movie.likes} dislikes={movie.dislikes} />
})
}
</div>
)
}
}
export default Home
CARD.js
import React, { PureComponent } from 'react'
import "./Card.css"
class Card extends PureComponent {
constructor(props) {
super(props)
this.state = {
active:false
}
this.toggleClass=this.toggleClass.bind(this)
}
toggleClass(){
const currentState = this.state.active;
this.setState({ active: !currentState });
}
handleClick(){
// How do I link this with the state in the HOME file
}
render() {
return (
<div className="cardbox">
<div className="cardtitle">{this.props.title}</div>
<div>{this.props.category}</div>
<div>{this.props.likes / this.props.dislikes}</div>
<i onClick={this.toggleClass} className={this.state.active?"fa fa-thumbs-up":"fa fa-thumbs-down"}></i>
<button onClick={this.handleClick}>Delete</button>
</div>
)
}
}
export default Card
React has one way data flow, so you need to write a function in your home component that changes the state, and then pass the function down to the card.js component.

Update state for component by event handle in other component in different file?

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)

Higher-order component (HOC) in React causing extra rendering of wrapped component

I'm using HOC to be able to wrap all components which should have translations. Each component has its translation file which is imported dynamically. Also they share some shared functionality. So, I've created HOC, which is a function taking component as an argument returning component with some extra features(e.g. modified componentDidMount).
Below is App.js and Translate.js(HOC).
App.js
import React, { Component } from 'react';
import translated from './Translate';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
translation: {
a: '',
},
translationRecieved: false
}
}
componentDidMount() {
console.log('APP mounted')
}
componentDidUpdate() {
console.log('APP did update')
if(!this.state.translationRecieved) {
this.setState({
translation: this.props.translation,
translationRecieved: true
})
}
}
render() {
console.log('APP renders')
const { t } = this.props
const { a } = this.state.translation
return (
<div className="App">
<p>This is state: a is {a}</p>
<hr/>
<p>Translated `a` is {t(a)}</p>
</div>
);
}
}
const Apptranslated = translated(App);
export default Apptranslated ;
Translate.js
import React from 'react';
import en from './en.json';
const translated = (WrappedComponent) => {
class HOC extends React.Component {
constructor(props) {
super(props);
this.state = {
translation: null
}
}
componentDidMount() {
console.log('HOC mounted')
this.setState({
translation: en
})
}
componentDidUpdate () {
console.log('HOC did update')
}
translate = (val = '') => `**| ${val} |**`;
render() {
console.log('HOC renders')
return <WrappedComponent
translation={this.state.translation} t={this.translate} {...this.props}/>;
}
}
return HOC;
};
export default translated;
Instead of define logic of loading translation in every component, I've used HOC. HOC loads translations into HOC's state and then pass it to wrapped component through the mechanism of props. Wrapped component receives passed props and saves it to the state (in componentDidUpdate). So my lifecycles are:
HOC renders
APP renders
APP mounted
HOC mounted
----initial phase ended---
----HOC fetched resources---
HOC renders
APP renders
APP did update
HOC did update
----APP modifies its state---
APP renders
APP did update
If I did the same with repetitive code (defining logic in each component)
App.js
import React, { Component } from 'react';
import en from './en.json';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
translation: {
a: '',
},
translationRecieved: false
}
}
componentDidMount() {
console.log('APP mounted')
if(!this.state.translationRecieved) {
this.setState({
translation: en,
translationRecieved: true
})
}
}
componentDidUpdate() {
console.log('APP did update')
}
translate = (val = '') => `**| ${val} |**`;
render() {
console.log('APP renders')
const { a } = this.state.translation
return (
<div className="App">
<p>This is state: a is {a}</p>
<hr/>
<p>Translated `a` is {this.translate(a)}</p>
</div>
);
}
}
export default App;
I would get
APP renders
APP mounted
APP renders
APP did update
Thus, I've extra rendering because I'm putting translations coming as props into component state. Why? Because they come async. So I've a choice: either write some logic in component to check whether translations have arrived and if not have some fallback options, or wait until they come and use state to safely use them in my App component.
Am I missing something or doing it wrong way? Or it is normal behavior of HOC?
Maybe Redux can solve this issue.

React Component with dynamic Sub-Components

I`m creating a react dynamic dialog where you can add functionality to the Dialog.
One way of doing this was with Composition, but I did not manage to do this via composition.
I`m not very experienced on React, so this was my first approach
I got my Modal component, and the modal has
export default class KneatModal extends React.Component {
constructor() {
super();
this.state = {
open: false
}
this.components = [];
I would add components like this
import CommentField from '../../../Modal/ModalContents/CommentField.jsx'
export default class DoApprove extends React.Component {
constructor() {
super();
}
componentDidMount() {
this._buildDialog();
}
_buildDialog() {
console.log("Building the Dialog");
this.modal.components.push(CommentField);
}
In that modal renderer, i have
<ModalContent components={ this.components } />
Then i the final renderer in ModalContent i try to render all attached components
render() {
var list = this.props.components.map((Component, key) => <Component/> );
return (
<div className='modal-contents'>
{list}
</div>
)
}
But the render method does not seems to work, i`ve tryed callin Component.render() instead of the component tag, but still could not make the sub-components render. =(
Would apreciate any help. Thanks
To be even more specific, this resumes on what im attempting
import PropTypes from 'prop-types';
import React from 'react';
import MyComponent1 from './MyComponent1.jsx'
import MyComponent2 from './MyComponent2.jsx'
export default class KneatModalContent extends React.Component {
constructor() {
super();
this.components = [MyComponent1, MyComponent2];
}
render() {
return (
<div className='modal-contents'>
{this.components.map(function (component, i) {
return <{ component } key= { i } />
})}
</div>
)
}
}

Categories