Can we call child component outside parent render function? - reactjs

Hi I'm new in React is there a way to call child component from parent component outside the render function ?? below is my sudo code,
any idea !!!!!!
var Parent React.createClass({
someFunction: function(){
//can I call Child component from here on every click
// as this will rerender the child component only on each click
// leaving parent component unrendered
},
render: function(){
}
})

The answer is NO. You've your answer in your question.
Let me explain. A component can be called as a child component only if it is used in the parent component, meaning, the child component should be used inside the render() of parent component. So, you cannot call a child component out of parent's render.
To achieve you requirement, you can use state to re-render the child component.
<script src="https://unpkg.com/babel-core#5.8.38/browser.min.js"></script>
<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="example"></div>
<script type="text/babel">
const Child = React.createClass({
render() {
return <h1>Hello, world!</h1>
}
})
const Parent = React.createClass({
getInitialState() {
return {
renderChild: false
}
},
onClick(){
this.setState({
renderChild: !this.state.renderChild
})
},
render(){
return <div>
<button onClick={this.onClick}>{this.state.renderChild ? 'Hide' : 'Show'} Child</button>
{
this.state.renderChild &&
<Child />
}
</div>
}
})
ReactDOM.render(<Parent />, document.getElementById('example') );
</script>

Related

How do I programmatically set focus on an element in a different component in React?

I have a parent component and two child components, call them child A and child B. I want to click a button in child A that will set focus on an element in child B. More specifically, I want to set focus on the first element under the <main> tag in child B.
How do I do so? Do I have to use React.createRef() in the parent and then pass that reference to both children or is there a more straightforward way to do this?
Creating a ref in the parent component like you mentioned and passing that to child B, and creating a function that will focus the ref and passing that to child A is one way of approaching it.
Example
class App extends React.Component {
ref = React.createRef();
handleClick = () => {
this.ref.current.focus();
};
render() {
return (
<div>
<ChildA onClick={this.handleClick} />
<ChildB innerRef={this.ref} />
</div>
);
}
}
function ChildA(props) {
return <button onClick={props.onClick}>Focus</button>;
}
function ChildB(props) {
return <input ref={props.innerRef} />;
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="root"></div>

ReactJS synthetic event for hit-state?

I recently did something like this
onHit(functionCall)
{
let attr = {};
attr["onKeyPress"] = functionCall;
attr["onClick"] = functionCall;
attr["onTouchEnd"] = functionCall;
return attr;
}
So that I can do this in my JSX
<a {...this.onHit((e)=>this.doSomething())} title="This has no href" tabIndex="0">This has no href</a>
Everything works as expected, where keypress, click, and touchdown all trigger the same event.
I created this onHit function because I'm building a web application where all action controls need to be accessible by keyboard, mouse and touch screen.
Before I continue using my custom onHit function, is there a more idiomatic way of doing this in ReactJS?
I think your solution is nice, but you could also create a custom component that takes the component/element type as prop, the onHit function as prop and uses that as event handler for all events, and that spreads the rest of the props.
Example
function MyComponent({ element: Element, onHit, ...rest }) {
return (
<Element onKeyPress={onHit} onClick={onHit} onTouchEnd={onHit} {...rest} />
);
}
class App extends React.Component {
render() {
return (
<MyComponent
element={"a"}
onHit={() => console.log("hit!")}
title="This has no href"
tabIndex="0"
>
This has no href
</MyComponent>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<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="root"></div>

React props from parent to children

I'm a debutant with react, i read the doc. It's a general question.
I understand how to pass a props from a child component to a parent component. But, I don't understand how to pass a props from a parent component to the child component.
So in the picture, to pass a props from list to app, i do that :
in list component :
interface Props {
onCreateDoc : () => void
}
And in my app component :
I call list with the props :
<List onCreateDoc={this.onCreateDocCb}/>
And i implement the function :
onCreateDocCb = () =>{
// code of function
}
But I don't know how to pass a props from app to form. How can i do that ? Thank you
It's easier to understand how to pass props then how to receive props.
You add props to your Form Component that way:
const bar = "bar"
const fooBar = () => console.log("fooBar")
<Form stringProps="foo" varProps={bar} funcProps={fooBar}/>
Inside your Form Component you can acces it via this.props.stringProps.
Here you find examples: https://facebook.github.io/react/docs/components-and-props.html
Edit: Here is a snippet with a App and a Form Component and props passed from App to Form
// Example stateless functional component
const Form = ({ label }) => (
<div style={{color: "blue"}}>{label}</div>
);
// Example class component
class App extends React.Component {
render() {
const {title} = this.props;
return (
<div>
<div>{title}</div>
<Form label="label from props" />
</div>
);
}
}
// Render it
ReactDOM.render(
<App title="title from props" />,
document.getElementById("react")
);
<div id="react"></div>
<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>

How to call a method in the React component in an external script

I would like to call in the external script, or console React components of the method
I tried to do so
componentDidMount(){
window.mwap = this;
}
but no use
enter image description here
please help me
The return value of ReactDOM.render() is actually the mounted instance of the component:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
inc() {
this.setState({count: this.state.count + 1});
}
render() {
return (
<div>
Count: {this.state.count}
</div>
)
}
}
const instance = ReactDOM.render(
<Counter />,
document.getElementById('app')
);
instance.inc();
<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>
If you need access to a deeply nested component, that's a bit more difficult, but this should get you started.

React what's the right way to get a parent props from its children

Be patient I'm new at React.
In this snippet (it doesn't work) I want,
in the CommentForm, to get the value of url props
from the CommentBox.
var CommentBox = React.createClass({
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList />
<CommentForm />
</div>
);
}
});
var CommentList = React.createClass({
render: function() {
return (
<div className="commentList">
Hello, world! I am a CommentList.
</div>
);
}
});
var CommentForm = React.createClass({
render: function() {
return (
<div className="commentForm">
Hello, my test url {this.props.url} !.
</div>
);
}
});
React.render(
<CommentBox url="api/comments" />,
document.getElementById('content')
);
What's the right way ?
and why the props is not available directly from the parent to the children ?
You need to explicitly pass the props from parent to child. Changing the render function of CommentBox will fix the problem:
var CommentBox = React.createClass({
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList />
//The next line is where you can pass the URL to the CommentForm
<CommentForm url={this.props.url}/>
</div>
);
}
});
Working jsfiddle adapted from your example: http://jsfiddle.net/kb3gN/10352/
The docs say "For parent-child communication, simply pass props." See
http://facebook.github.io/react/tips/communicate-between-components.html
As an alternative to explicitly passing props, React's undocumented context feature is closer to what you're looking for:
https://www.tildedave.com/2014/11/15/introduction-to-contexts-in-react-js.html
and is on the roadmap for 1.0 https://facebook.github.io/react/blog/2014/03/28/the-road-to-1.0.html#context.
That said, passing props is the normal pattern.

Resources