I'm new to reactjs, I'm trying to communicate 2 component and render again one of them.
I have the following:
layout.js
import React from 'react';
...
class Layout extends React.Component {
constructor(props) {
super(props);
this.state = {
toolbar: 'none'
};
}
getChildContext() {
let me = this;
return {
changeToolbar: function (newToolbar) {
me.setState({ toolbar: newToolbar })
}
}
}
render() {
const {Search, Nav} = this.props;
return (
<div className="wrap">
<Header Search={Search} />
<Toolbar toolbar={this.state.toolbar} />
<div className="main">
<Nav />
<div className="content">
{this.props.children}
</div>
</div>
</div>
)
}
}
Layout.childContextTypes = {
changeToolbar: React.PropTypes.func
}
export default Layout;
toolbar.js
import React from 'react';
...
import ProductToolbar from '../components/toolbar/productToolbar';
import SalesToolbar from '../components/toolbar/salesToolbar';
class Toolbar extends React.Component {
static propTypes = {
toolbar: React.PropTypes.string.isRequired
};
state = {
toolbar: this.props.toolbar
};
componentWillReceiveProps(next_props) {
this.setState({toolbar: next_props.toolbar})
}
render () {
let bar = <div>{this.state.toolbar} undefined</div>;
switch (this.state.toolbar) {
case 'productToolbar':
bar = ProductToolbar;
break;
case 'salesToolbar':
bar = SalesToolbar;
break;
};
return (
<div className='toolbar show'>
{bar}
</div>
)
}
}
export default Toolbar;
productToolbar.js
import React from 'react';
export default class ProductToolbar extends React.Component {
render() {
return (
<div>
productToolbar
</div>
);
}
};
productPage.js
import React, {Component} from 'react';
...
class ProductPage extends React.Component {
componentDidMount() {
this.context.changeToolbar('productToolbar');
};
render() {
return (
<div>Page</div>
);
}
};
ComisionPage.contextTypes = {
changeToolbar: React.PropTypes.func
}
export default ProductPage;
when desire is loaded productPage.js create a special toolbar with options for Productpage.
I pass the name of the toolbar to render the new view, but it does not, missing or that I'm doing wrong?
another best solution was to pass directly toolbar
productPage.js
import ProductToolbar from '../components/toolbar/productToolbar';
...
componentDidMount() {
this.context.changeToolbar(ProductToolbar);
};
It not works for me
Just to make sure that you are rendering the element. Can you please change you switch statement to:
switch (this.state.toolbar) {
case 'productToolbar':
bar = <ProductToolbar />;
break;
case 'salesToolbar':
bar = <SalesToolbar />;
break;
};
Also, consider using a store (Redux, AltJs?) instead of context since they can get a bit complex on large apps (...I experienced the pain, until I switch to the 'store' approach)
Related
Currently i am exporting only one funtin like this and it works great
import React from "react";
import SocialLogin from "from somewwhere";
class GoogleButton extends React.Component {
render() {
const { fontClass, triggerLogin, ...props } = this.props;
return (
<div className="">
Google
</div>
);
}
}
export default SocialLogin(GoogleButton);
But when I try to export multiple functions, it doesn't work.
import React from "react";
import SocialLogin from "from somewhere";
class GoogleButton extends React.Component {
render() {
const { fontClass, triggerLogin, ...props } = this.props;
return (
<div className="">
Google
</div>
);
}
}
class FacebookButton extends React.Component {
render() {
const { fontClass, triggerLogin, ...props } = this.props;
return (
<div className="">
Facebook
</div>
);
}
}
export {
SocialLogin(GoogleButton),
SocialLogin(FacebookButton);
}
Can anyone tell me why it doesnt work? It works when i do like this
export {
SomeFunc,
AnotherFun,
}
But what's wrong with it if i put it inside a functin? Can anyone tell me how can i do it?
You cam simply do this.
import React from "react";
import SocialLogin from "from somewhere";
export class GoogleButton extends React.Component {
render() {
const { fontClass, triggerLogin, ...props } = this.props;
return (
<div className="">
Google
</div>
);
}
}
export class FacebookButton extends React.Component {
render() {
const { fontClass, triggerLogin, ...props } = this.props;
return (
<div className="">
Facebook
</div>
);
}
}
Or you can do this.
.... Existing components
export default {
SocialLoginGoogle: SocialLogin(GoogleButton),
SocialLoginFacebook: SocialLogin(FacebookButton)
}
The below one works as it is considering object's key and value has the same name. Hence, shorthand.
export {
SomeFunc,
AnotherFun,
}
I am not able to use this switcher method in my react app. which is build using class components
Suggest me way to use this switcher method of useThemeSwitcher() function in class components.
How can i Use or (write )this function in my web app.???
In this method switcher function is used in functional component..
import React from "react";
import "./App.css";
import { useThemeSwitcher } from "react-css-theme-switcher";
import { Switch } from "antd";
function App() {
const [isDarkMode, setIsDarkMode] = React.useState("false");
const { switcher, themes } = useThemeSwitcher();
const toggleTheme = (isChecked) => {
setIsDarkMode(isChecked);
switcher({ theme: isChecked ? themes.dark : themes.light })
};
return (
<div className="main fade-in">
<Switch checked={isDarkMode} onChange={toggleTheme} />
</div>
);
}
export default App;
I want use switcher function in this code..
import React from "react";
import { Layout, Button, Menu, Popconfirm, Dropdown, Select } from 'antd';
import { useThemeSwitcher } from "react-css-theme-switcher";
import { Switch, Input } from "antd";
class Header extends React.Component {
constructor(props) {
super(props);
this.toggleTheme = this.toggleTheme.bind(this);
this.state = {
isDarkMode:false,
};
}
toggleTheme = (isChecked)=>
{
this.setState({isDarkMode:isChecked ? true : false})
}
render() {
return (
<div className="main fade-in">
<Switch checked={this.state.isDarkMode} onChange={this.toggleTheme} />
</div>
)
}
}
export default Header;
Since it's a hook you'll need to use it in a functional component. Simply translate your class component to a functional one.
const Header = () => {
const [isDarkMode, setIsDarkMode] = useState(false);
// Now we can use it
const { switcher, themes } = useThemeSwitcher();
return <div className="main fade-in">
<Switch checked={this.state.isDarkMode} onChange={setIsDarkMode} />
</div>;
};
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 trying to use a function, which is in a different component from App.js.
and I'm having the syntax error, I don't know what did I do wrong. I have a button in App.js and when I click on it, that function from another component that I've mentioned earlier should trigger.
app.js:
import React from 'react';
import {shaking} from './components/Tree/Tree.js';
class App extends React.Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
shaking();
console.log("done !");
}
render() {
return (
<div>
<Tree className='tree' />
<Apples />
<Basket />
<br/>
<button className="start-btn" onClick={this.handleClick}>Start !</button>
<br/>
</div>
);
}
};
export default App;
And this is my another component:
import React from 'react';
import TreeSvg from './Tree-svg/TreeSvg.js';
import './Tree.sass';
export function shaking(){
const tree = document.getElemenetsByClassName(".tree-img")[0];
tree.classList.add("apply-shake");
console.log('shaked!');
}
class Tree extends React.Component{
constructor() {
super();
this.shaking = this.shaking.bind(this);
}
shaking() {
this.setState({shaked:'1'});
const tree = document.getElemenetByClassName(".tree-img");
tree.classList.add("apply-shake");
console.log('shaked!');
}
render(){
return(
<div className="tree-img">
<TreeSvg />
</div>
);
}
};
export default Tree;
Make your Tree component like this
import React from 'react';
import TreeSvg from './Tree-svg/TreeSvg.js';
import './Tree.sass';
export function shaking(){
const tree = document.getElementsByClassName(".tree-img")[0];
tree.classList.add("apply-shake");
console.log('shaked!');
}
class Tree extends React.Component{
constructor() {
super();
this.state = {
shaked : ''
}
shaking() {
this.setState({shaked:'1'});
const tree = document.getElementByClassName(".tree-img");
tree.classList.add("apply-shake");
console.log('shaked!');
}
render(){
return(
<div className="tree-img">
<TreeSvg />
</div>
);
}
};
export default Tree;
You do have 2 syntax errors in your code. Both are located at the Tree component file.
At your exported function (Line 6):
const tree = document.getElemenetsByClassName(".tree-img")[0];
replace Elemenets with Elements.
At the class method shaking() (Line 21):
const tree = document.getElemenetByClassName(".tree-img"); replace Elemenet with Element
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>
)
}
}