Parent Component is like below
import React, { useState } from "react";
import EntityDefinition from "./EntityDefinition";
export default function EntitySelection(props) {
const testFun = () => {
console.log("Function activated");
};
return (
<>
<div>
<EntityDefinition
testFun={testFun}
/>{/**Calling a Class based Component*/}
</div>
</>
);
}
Class based Component (Child)
import React from "react";
import { ComboBox, DropdownOption, Button } from "react-widgets";
import axios from "axios";
export default class EntityDefinition extends React.Component {
render() {
return (
<React.Fragment>
<div>
{" "}
<Button onClick={this.testFun}>Close</Button>{" "} {/*/Calling the function passed*/}
</div>
</React.Fragment>
);
}
}
but when i clicked the button the testFun function is not being called.
i tried something like onClick={this.state.testFun} , onClick={testFun}
but nothing is happening.
can someone point what am i doing wrong here.
testFun is a prop. So use this.props.testFun
onClick={this.props.testFun}
testFun is a prop, and you are using the ES6 class component, and it receives the props as a props object, so you can try accessing it as below
onClick={this.props.testFun}
You need to refer to props passed to a class based components using this.props from inside the class based components:
Docs
In your case, you should change the onClick listener to this:
<Button onClick={this.props.testFun}>
Related
I am trying to pass the value of the text area from some component in reactjs to be used in another react component. the component value is stored in the first component in a useState hook so I want to access it in another component and run map() function around it . Is this possible in reactjs ? I don't want to put the whole thing in app.js because that is just plain HTML which I don't want. I want to use reactjs function components instead ?
first component:
import React, { useState, useRef, useEffect } from "react";
function Firstcomp() {
const [quotes, setQuotes] = useState(["hi there", "greetings"]);
const reference = useRef();
function sub(event) {
event.preventDefault();
setQuotes((old) => [reference.current.value, ...old]);
console.log(quotes);
return;
}
return (
<>
<div>
<div>
<div>
<h4>jon snow</h4>
</div>
<form onSubmit={sub}>
<textarea
type="textarea"
ref={reference}
placeholder="Type your tweet..."
/>
<button type="submit">Tweet</button>
</form>
{quotes.map((item) => (
<li key={item}>{item}</li>
))}
{/* we can use card display taking item as prop where it
will do the job of filling the <p> in card entry */}
</div>
</div>
</>
);
}
export default Firstcomp;
second component
import React from "react";
function SecondComp(props) {
return (
<div>
<p>{props.message}</p>
</div>
);
}
export default Secondcomp;
Use a global management state like Recoil, Redux ot Context
import React from 'react';
export const UserContext = React.createContext();
export default function App() {
return (
<UserContext.Provider value="Reed">
<User />
</UserContext.Provider>
)
}
function User() {
const value = React.useContext(UserContext);
return <h1>{value}</h1>;
}
on the exemple above we used useContext hook to provide a global variable "value", even its not declared directly in User component, but you can use it by calling the useContext hook.
in this exemple the return value in the user component is "Reed"
First off, I'm newer to react so please feel free to critique any sort of architectural problems I have, I feel like there's a better way to write this but I've been struggling for an hour trying to get it to work.
Parent Element (TileGrid):
import React, { Component } from 'react'
import Tile from './Tile.js';
export default class TileGrid extends Component {
constructor(props) {
super(props);
}
updateTileData(value) {
{/* Do something with value here */}
}
render() {
this.test()
return (
{/* The Tile component is a custom button with some richer features. */}
<Tile name='Dog' image='dog' />
)
}
}
Child Element (Tile):
import React from 'react';
import ButtonBase from '#mui/material/ButtonBase';
import './styles/Tile.css';
function Tile(props) {
return(
<div className="Tile">
<ButtonBase onClick={/* This is where the Tile needs to call updateTileData in TileGrid */}>
Button
</ButtonBase>
</div>
);
}
export default Tile;
So there's a function inside of TileGrid called updateTileData that is going to take some data and use it to update the state of TileGrid. The Tile component exists as a child within the TileGrid component. I've tried all sorts of stuff on here but this seems like a simple task to do, is there a better way to write this functionality? I'm not tied down to anything in the code, please tell me if there's a better way to do this. I'm still learning this framework and this issue has me hung up. Thanks, Archer.
pass the function from parent to child as a prop example :
<Child func={this.functionInParent} />
props.func() //called inside child
you need to pass a prop to child Element and Call it.
import React, { Component } from 'react'
import Tile from './Tile.js';
export default class TileGrid extends Component {
updateTileData(value) {
{/* Do something with value here */}
}
render() {
this.test()
return (
{/* The Tile component is a custom button with some richer features. */}
<Tile name='Dog' image='dog' setValue={this.updateTileData} />
)
}
}
child Element :
import React from 'react';
import ButtonBase from '#mui/material/ButtonBase';
import './styles/Tile.css';
function Tile(props) {
return(
<div className="Tile">
<ButtonBase onClick={()=>props.setValue("your value")}>
Button
</ButtonBase>
</div>
);
}
export default Tile;
I have a Component like this:
class GlobalComponent extends React.Component{
select= (e) => {
this.props.select(); // must be implemented in another component and not parent
};
render(){
return(
<div>
{this.state.data}
<Button onClick={this.select}>Select</Button>
</div>
);
}
}
function mapStateToProps(state) {
return state.data
}
const mapDispatchToProps = (dispatch, props) => ({
select: () => dispatch(select()),
});
export default connect(mapStateToProps, mapDispatchToProps)(GlobalComponent );
I am importing this component in the root of my app - app.js like this:
<GlobalComponent />
The problem is this actionselect. I know I can pass it from global state or parent component with props (for the example):
<GlobalComponent select={this.select} />
or with mapDispatchToProps
, but the problem is that the component is defined only in one place, otherwise I need to import the GlobalComponent in almost all components.
What I want is to import the component once (somewhere in the root) and then somehow in a component that uses GlobalComponent define a function, which will NOT execute select, but implement select and it is only for the click event in the GlobalComponent:
export default class ComponentThatUsesGlobal extends React.Component {
executeWhenGlobalComponentBtnIsClicked = () => {
}
}
Is this possible and is it good approach or it is better just to import the component everywhere ?
I am using and Redux.
I need to understand the export and import statement in React (Might involve the use of HOC)
So I have a higher component known as withclass.js like this
import React from 'react';
const withClass = (WrappedComponent, ClassName) => {
console.log(WrappedComponent)
console.log(ClassName)
return (props) => (
<div className={ClassName}>
<WrappedComponent />
</div>
)
}
export default withClass;
And inside our App.js, we do something like this
import withClass from '../hoc/withclass.js';
import classes from './App.css';
class App extends Component {
//some code here
//------ include render and return
export default withClass(App, classes.App);
Now, In Export statement I understand that he is passing two parameters which our withClass function requires as parameters but shouldn't he import something in withclass.js? How does our withclass.js receive those arguments?
Also, how does our return function (in withclass.js) get access to props here? (for example we passed props as an argument to our return function in withclass.js)?
I wasn't quite clear what you are asking for but regarding passing the argument you can do something like shown below. If I can get a little more explanation, I will update my answer.
import withClass from '../hoc/withclass.js';
class App extends Component {
//some code here
//------
return (
<Aux>
<button onClick={this.showPersonTrueHandler}>Show Persons </button>
<Ccockpit
coatiitle = {this.props.title}
cocPersonState = {this.state.showPerson}
cocperson = {this.state.person.length}
toggler = {this.togglerPersonHandler} />
{person}
</Aux>
)
}
}
export default withClass((parameter1, parameter2)=>{
//perform any action here...
})(App);
I have a modal component with two methods that show/hide the modal. How can I call those methods from another component?
This is the code for the Modal:
// Dependencies
//==============================================================================
import React from 'react'
import Modal from 'boron/DropModal'
// Class definition
//==============================================================================
export default class RegistrationModal extends React.Component {
showRegistrationModal() {
this.refs.registrationModal.show()
}
hideRegistrationModal() {
this.refs.registrationModal.hide()
}
render() {
return (
<Modal ref="registrationModal" className="modal">
<h2>Meld je aan</h2>
<button onClick={this.hideRegistrationModal.bind(this)}>Close</button>
</Modal>
)
}
}
You can call a components method from the outside as long as you keep a reference to the component. For example:
let myRegistrationModal = ReactDOM.render(<RegistrationModal />, approot );
// now you can call the method:
myRegistrationModal.showRegistrationModal()
It's a bit cleaner if you pass a reference to the modal to another component, like a button:
let OpenModalButton = props => (
<button onClick={ props.modal.showRegistrationModal }>{ props.children }</button>
);
let myRegistrationModal = ReactDOM.render(<RegistrationModal />, modalContainer );
ReactDOM.render(<OpenModalButton modal={ myRegistrationModal }>Click to open</OpenModalButton>, buttonContainer );
Working example: http://jsfiddle.net/69z2wepo/48169/
You cant call it from another component, because its a method belong to RegistrationModal component, but you can refactor your code so you can call it
export function hideRegistrationModal() {
console.log("ok");
}
export default class RegistrationModal extends React.Component {
render() {
return (
<Modal ref="registrationModal" className="modal">
<h2>Meld je aan</h2>
<button onClick={hideRegistrationModal}>Close</button>
</Modal>
)
}
}
now you can call from anywhere but you need to import it first like this
import { RegistrationModal, hideRegistrationModal } from 'path to modal.js'
// ^-- Component name ^-- Method
What you want to do is create a parent component which will handle the communication between your modals.
A really great example and explanation can be found here: ReactJS Two components communicating
This is a good approach because it keeps your components decoupled.