How to show a component randomly on every page load? (React) - reactjs

How can I show a component randomly on every page load (using React)?
For example, I have two components:
<ComponentOne /> and <ComponentTwo />
I would like to randomly show one of the components on each page load.
Should I do it in componentDidMount()?
class MyComponent extends React.Component {
loadRandomComponent() {
// return <ComponentOne /> || <ComponentTwo />
}
componentDidMount() {
this.loadRandomComponent();
}
}

See if that helps
class ComponentThree extends React.Component {
render() {
return <div>ComponentThree</div>;
}
}
class ComponentTwo extends React.Component {
render() {
return <div>ComponentTwo</div>;
}
}
class ComponentOne extends React.Component {
render() {
return <div>ComponentOne</div>;
}
}
class Hello extends React.Component {
randomize(myArray) {
return myArray[Math.floor(Math.random() * myArray.length)];
}
render() {
var arr = [<ComponentOne />, <ComponentTwo />, <ComponentThree />]
return <div>Hello {this.randomize(arr)}</div>;
}
}

Related

this.props.parentFunction is not a function

This is a simple React.js script, but couldn't find the cause. I think this issue is a common doubt for initial React developers. Please help.
The error showing is "this.props.parentClick is not a function".
class App extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
parentClick() {
}
render() {
return (
<div>
<Test childClick={this.parentClick}/>
</div>
);
}
}
class Test extends Component{
constructor(props){
super(props);
this.childClick = this.childClick.bind(this);
}
childClick(){
this.props.parentClick();
}
render() {
return (
<div>
<button onClick={()=>this.childClick()}>click</button>
</div>
);
}
}
render(<App />, document.getElementById('root'));
Here is the code in stackblitz.com.
https://stackblitz.com/edit/react-3zt7qm
Your prop is called childClick not parentClick
Try with:
class App extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
parentClick() {
}
render() {
return (
<div>
<Test parentClick={this.parentClick}/> // Here the name of your prop should be parentClick
</div>
);
}
}
This function inside of your Test component:
childClick(){
this.props.parentClick();
}
should call this.props.childClick(), because thats the prop you passed into the Test component.

React: How can you access the class name of a parent component from a child without passing it down as props?

Say you have a parent component:
// ParentComponent
class ParentComponent extends React.Component {
render() {
return(
<ChildComponent/>
)
}
}
From inside the child component, is there a way to access the class name of the parent component without passing this down as props?
// ChildComponent
class ChildComponent extends React.Component {
// ?????
getParentComponentName() {
return this.??? // Should return "ParentComponent"
}
render() {
return(
<div/>
)
}
}
I'd prefer to be able to access this without passing it down as props. Thank you!
You need to access ReactInternalFiber like
class Child extends React.Component {
constructor(props) {
super(props);
this.state = { name: '' }
}
getParentName = () =>{
this.setState({ name: this._reactInternalFiber._debugOwner.type.name })
}
render() {
return (
<div>
<h1>Name: {this.state.name}</h1>
<button onClick={this.getParentName}>Get Parent Name</button>
</div>
)
}
}

Call function from another React component

My first component is as follow:
const hellos = ['Hola', 'Salut', 'Hallo', 'Ciao', 'Ahoj', 'Annyeong-haseyo', 'Aloha', 'Howdy', 'Ni Hao', 'Konnichiwa']
export class Welcome extends Component {
constructor(props) {
super(props);
this.state = {
errors: []
};
}
sayHello = function() {
return hellos[Math.floor((Math.random()*hellos.length))];
}
render() {
return (
<div className="Welcome">
</div>
);
}
}
I want to be able to call sayHello() from another component. All answers I've seen so far talk about parent and child relationships but in this case the two components don't have any relationship. I thought of something like this but it doesn't do the job:
import { Welcome } from './Welcome'
export const Life = () => (
<div className="Life">
<p>{ Welcome.sayHello() }</p>
</div>
)
I would like to get a random element of the hellos array printed in Life.
There are a number of ways you could achieve this:
You can do this by creating the sayHello function and using it simply as a named-function.
hello.js
const hellos = ['Hola', 'Salut', 'Hallo', 'Ciao', 'Ahoj', 'Annyeong-haseyo', 'Aloha', 'Howdy', 'Ni Hao', 'Konnichiwa'];
const sayHello = function() {
return hellos[Math.floor((Math.random()*hellos.length))];
};
export { sayHello };
Then you can import into which ever component you wish to share the functionality:
import { sayHello } from './hello';
class CompA extends React.Component {
render() {
return <span>{sayHello()}</span>;
}
}
class CompB extends React.Component {
render() {
return <span>{sayHello()}</span>;
}
}
render(<span>
<CompA />
<CompB />
</span>, document.querySelector('#app'));
Created a https://www.webpackbin.com/bins/-KkgrwrMGePG4ixI0EKd
Another way, is to simply define your sayHello Function as static.
static sayHello() {
return hellos[Math.floor((Math.random()*hellos.length))];
}

React propTypes errors not showing

I'm having problems with React propTyoes. I'v created a component that require 2 props to work as you guys can see in the code below.
When I use the component in the App file, passing just 1 prop, without the "stateSidebarVisible" it doesn't throw me any error/warning from react...
(I read a lot of things about the NODE_ENV production/development, I searched in my node for process.env and didnt found the NODE_ENV variable by the way).
Any clue?
FFMainHeader
export default class FFMainHeader extends React.Component {
render() {...}
}
FFMainHeader.propTypes = {
stateSidebarVisible: React.PropTypes.bool.isRequired,
handleSidebarChange: React.PropTypes.func.isRequired
};
App
This is where i call the FFMainHeader component.
export default class FFMainApp extends React.Component {
.......
render() {
return (
<div id="FFMainApp">
<FFMainHeader
handleSidebarChange={this.onSidebarChange} />
<FFMainSidebar />
</div>
);
}
}
EDIT
export default class FFMainHeader extends React.Component {
constructor(props) {
super(props);
this.clickSidebarChange = this.clickSidebarChange.bind(this);
}
clickSidebarChange(e) {
e.preventDefault();
(this.props.stateSidebarVisible) ?
this.props.stateSidebarVisible = false :
this.props.stateSidebarVisible = true;
this.props.handleSidebarChange(this.props.stateSidebarVisible);
}
render() {
return (
<header id="FFMainHeader">
<a href="#" onClick={this.clickSidebarChange}>
Abre/Fecha
</a>
</header>
);
}
}
FFMainHeader.propTypes = {
stateSidebarVisible: React.PropTypes.bool.isRequired,
handleSidebarChange: React.PropTypes.func.isRequired
};

How to render react component determined by string in TSX

I want to achieve navigation based on hash change in url.
for example for url index.html#HomePage the app will load HomePage component.
import { HomePage } from '../components/homepage'
import { AnotherPage } from '../components/anoterpage'
export class NavigationFrame extends React.Component<any, State> {
constructor(props) {
super(props);
this.state = { pageName: this.pageNameFromUrl() };
}
onHashTagChanged = () => {
this.setState({pageName: this.pageNameFromUrl()});
}
public render() {
var Page = this.state.pageName as any;
return <Page /> //this renders <homepage /> when this.state.pageName = "HomePage";
}
}
is there any way how to dynamically create component based on string?
class CustomComponent extends React.Component{
render(){
return (
var DynamicComponent = this.props.component;
return <DynamicComponent />;
)
}
}
import it into your file and use like below,
return (
<CustomComponent component={this.state.pageName} />
);

Resources