score:3

Accepted answer

in react if you want to render same component multiple times and treat them as different then you need to provide them a unique key. try the below code.

{toggle ? <a key="a" prop={"a"} /> : <a key="b" prop={"b"} />}

score:1

react will only call the constructor once. that's the expected outcome. looks like you're trying to update the state of the component a based on the props. you could either use the prop directly or use the componentdidupdate lifecycle method, as henry suggested. another way is using the static method getderivedstatefromprops to update the state based on the prop passed.

static getderivedstatefromprops(props, state) {
    return ({
        content: props.prop
    });
}

score:2

since that ternary statement renders results in an <a> component in either case, when the <app>'s state updates and changes toggle, react sees that there is still an <a> in the same place as before, but with a different prop prop. when react re-renders it does so by making as few changes as possible. so since this is the same class of element in the same place, react doesn't need to create a new element when toggle changes, only update the props of that <a> element.

essentially, the line

{toggle ? <a prop="a"/> : <a prop="b"/> }

is equivalent to

<a prop={ toggle ? "a" : "b" }/>

which perhaps more clearly does not need to create a new <a> component, only update the existing one.

the problem then becomes that you set the state.content of the <a> using props.prop in the constructor, so the state.content is never updated. the cleanest way to fix this would be to use props.prop in the render method of the <a> component instead of state.content. so your a class would look like this:

class a extends component {
    render() {
        const { prop } = this.props;
        return <div>{ prop }</div>;
    }
}

if you must take the prop prop and use it in the <a> component's state, you can use componentdidupdate. here's an example:

class a extends component {
    constructor(props) {
        super(props);
        this.state = {content: props.prop};
    }

    componentdidupdate(prevprops) {
        if (prevprops.prop !== this.props.prop) {
            this.setstate({content: this.props.prop});
        }
    }

    render() {
        const { content } = this.state;
        return <div>{ content }</div>
    }
}

Related Query

More Query from same tag