How can I get intl.formatMessage from parent component? I wrapped parent component with injectIntl and want send intl.formatMessage to child component. Can someone help me with that? Thank you!
Parent component
import Car from "./test3";
import { injectIntl } from "react-intl";
class Intl extends React.Component {
render() {
return (
<div>
<h1>Who lives in my garage?</h1>
<Car brand="Ford" />
</div>
);
}
}
export default injectIntl(Intl);
Child component
import { FormattedMessage} from "react-intl";
class Car extends React.Component {
yearsTranslation = () =>
this.props.intl.formatMessage({ id: "search.filter.maturity.years" });
render() {
return <h2>Hello {this.yearsTranslation()}!</h2>;
}
}
export default Car;
Just pass the prop down, like so :
class Intl extends React.Component {
render() {
return (
<div>
<h1>Who lives in my garage?</h1>
<Car brand="Ford" intl={this.props.intl}/>
</div>
);
}
}
export default injectIntl(Intl);
I thinks intl is available in the context. Please check the documentation.
Related
How can I share the data value that I have from the handleClick function inside the Module class to the InputSelect class, all the classes are in the same file?? I'm not using Redux.
I can't use props because there is not a relationship between these classes..
Should I nest all the classes??
Any suggestion??
import React, { useState } from "react";
const array = [ ];
class InputSelect extends React.Component {
render() {
return (
<div>
{ 'Put it here........' }
</div>
)
}
}
class Module extends React.Component {
handleClick(e) {
console.log(e.currentTarget.textContent);
}
render() {
return (
<div
onClick={this.handleClick}
>
{this.props.id}
</div>
);
}
}
function App() {
return (
<div>
<Menu availableModules={array} />
</div>
);
}
export default App;
Correctly stated by #Federkun above, you should use React context.
Check the react docs here
Can you help me in changing this React stateless functional component to React class based component including the withRouter and history object as given?
const Menu = withRouter(({history}) => (
<AppBar>
</AppBar>
))
export default Menu
class Menu extends React.Component {
render() {
// you can use this.props.history anywhere in the class
const { history } = this.props;
return <AppBar>...</AppBar>
}
}
export default withRouter(Menu);
First, create your class component and then, create a constructor for the class. You can then define the states required inside the constructor, something like this-
export default class Menu extends React.Component {
constructor(props) {
super(props);
this.state = {
SomeVar: xyz,
AnotherVar: undefined
}
}
render() {
return withRouter(({history}) => (
<AppBar> </AppBar>
));
}
}
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 wrote some code to exercise in React. I would like somebody to explain me why if the target of the clickChange is clicked (h3), state does not update.
Below there is my main App component:
import React, { Component } from "react";
import Prova from "./components/prova";
import "./App.css";
class App extends Component {
state = {
name: "giovanni"
};
clickChange = () => {
this.setState({ name: "joe" });
};
render() {
return (
<div>
<h3>SONO APP</h3>
<Prova onClick={this.clickChange} provaProp={this.state.name} />
</div>
);
}
}
export default App;
Below another Component, imported and called (and rendered) into the main App component.
Now, as you can see i set up a method, clickChange, that, once you click on the element, it SHOULD change the state, switching "giovanni" to "joe".
The question is: why it does not trigger? I know that the rendered part of the code it's in the other component, prova, but the state it's in my App component. Therefore, the state is changed internally, without any reference to the external.
import React, { Component } from "react";
class Prova extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<p>{this.props.provaProp}</p>
</div>
);
}
}
export default Prova;
I think you just forgot to trigger the onClick event inside your Prova component.
import React, { Component } from 'react';
class Prova extends Component {
constructor(props) {
super(props)
}
render() {
return (
<div onClick={this.props.onClick}>
<p>{this.props.provaProp}</p>
</div>
)
}
}
export default Prova;
demo
class App extends React.Component {
state = {
name: "giovanni"
};
clickChange = () => {
this.setState({ name: "joe" });
};
render() {
return (
<div>
<h3>SONO APP</h3>
<Prova onClick={this.clickChange} provaProp={this.state.name} />
</div>
);
}
}
class Prova extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div onClick={this.props.onClick}>
<p>{this.props.provaProp}</p>
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
For props you will get it in componentWillReceiveProps()
Usage in child component
componentWillReceiveProps(props){
console.log(props.provaProps);
}
So whenever a state of parent component gets updated it updates the props as well but to get updated props in child components we use componentWillReceiveProps().
See more here
Additionally you forgot to attach click event in props
<div onClick={this.props.onClick}>
<p>{this.props.provaProp}</p>
</div>
Because you have not tiggered onClick event in child Component.
change code in Prova component as
<div onClick={this.props.onClick}>
<p>{this.props.provaProp}</p>
</div>
resolved react example here
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>
)
}
}